@RequestMapping("/user")
@Controller
public class UserController {
@Autowired
protected UserService userService;
@Autowired
@Qualifier("org.springframework.security.authenticationManager")
protected AuthenticationManager authenticationManager;
@RequestMapping(method = RequestMethod.POST)
public String register(@Valid @ModelAttribute("user") User user,
BindingResult result, HttpServletRequest request, ModelMap modelMap) {
//valiate user information
if (result.hasErrors()) {
return "user/register";
}
//save user information into database
userService.register(user);
// After successfully Creating user
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
user.getUsername(), user.getPassword());
// generate session if one doesn't exist
request.getSession();
token.setDetails(new WebAuthenticationDetails(request));
Authentication authenticatedUser = authenticationManager
.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authenticatedUser);
return "redirect:/";
}
Note:
@Qualifier("org.springframework.security.authenticationManager")
I met NoSuchBeanDefinitionException at first:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [org.springframework.security.authentication.AuthenticationManager] is defined: expected single matching bean but found 2: [org.springframework.security.authentication.ProviderManager#0, org.springframework.security.authenticationManager]
This is because:
There are two AuthenticationManagers in the context:
org.springframework.security.authenticationManager is populated with authentication providers explicitly declared in
org.springframework.security.authentication.ProviderManager#0 is populated with implicitly declared providers (remember me, anonymous and so on) and delegates the authentication request to org.springframework.security.authenticationManager as a fallback.
so what we need is @Qualifier("org.springframework.security.authenticationManager").
4 comments:
Gosh, I’ve been looking about this specific topic for about an hour, glad i found it in your website!
online pharmacy
Thanks for your share! very impressive!
aroma therapy
Great work keep it coming, best blog on earth
clomid
This blog is bookmarked! I really love the stuff you have put here.
cheap nolvadex
Post a Comment