Friday, November 19, 2010

Auto login after successful registeration in Spring Security 3

When user successfully register, auto login user instead of redirecting them to login page and asking them to login again. Here is the solution I found for Spring Security 3.

@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:

gequaire said...

Gosh, I’ve been looking about this specific topic for about an hour, glad i found it in your website!

online pharmacy

naxamast said...

Thanks for your share! very impressive!

aroma therapy

qeniwait said...

Great work keep it coming, best blog on earth

clomid

hiciscat said...

This blog is bookmarked! I really love the stuff you have put here.

cheap nolvadex