views:

69

answers:

2

hey all i want to make an auto login after successful registration in spring meaning: i have a protected page which requires login to access them and i want after registration to skip the login page and make an auto login so the user can see that protected page, got me ? i am using spring 3.0 , spring security 3.0.2 how to do so ?

A: 

I'm not sure if you are asking for this, but in your Spring Security configuration you can add a "remember-me" tag. This will manage a cookie in your client, so next time (if the cookie hasn't expired) you'll be logged automatically.

<http>
    ...
    <remember-me />
</http>
Sinuhe
that's not what um asking about
sword101
A: 

This can be done with spring security in the following manner(semi-psuedocode):

    import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

@Controller
public class SignupController
{

    @Autowired
    RequestCache requestCache;

    @Autowired
    protected AuthenticationManager authenticationManager;

    @RequestMapping(value = "/account/signup/", method = RequestMethod.POST)
    public String createNewUser(@ModelAttribute("user") User user, BindingResult result,  HttpServletRequest request, HttpServletResponse response)
    {
        //After successfully Creating user
            authenticateUserAndSetSession(user, request);

        return "redirect:/home/";
    }

    private void authenticateUserAndSetSession(User user,
        HttpServletRequest request)
{
    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);
}

}

Update: to only contain how to create the session after the registration

Spring Monkey
not correct, i already know the landing page but it requires login to see it and i don't want to go to the login page and want to make an internal auto login, got me ?
sword101
I have updated my code to do login automatically after the signup.
Spring Monkey
i got the following exception ??? org.springframework.security.authentication.BadCredentialsException: Bad credentials
sword101
previous exception solved, but i got the following exception org.springframework.security.access.AccessDeniedException: Access is denied more details here:http://stackoverflow.com/questions/3923296/access-denied-when-trying-to-make-an-auto-login
sword101