views:

419

answers:

2

Hi,

I'm using Spring Security for securing HTTP requests to a website. The primary usage is for securing pages such that the user is redirected to the login page when trying to access those pages.

However, I have a further requirement. In my model, I can flag a user's password as being temporary such that, when they successfully login, they should be automatically forced to change their password. Once the password is changed, they should then be forwarded on to the page they were originally trying to access.

Has anyone used Spring Security for this purpose? Do I need to create my own custom filter?

Thanks,

Andrew

+1  A: 

In Spring Security 3.0 you can implement a custom AuthenticationSuccessHandler.

In this handler you can redirect a user with temporary password to the password change page instead of the originally requested page. After password is changed, you may redirect user to the originally requested page using SavedRequestAwareAuthenticationSuccessHandler, which is the default handler implementation.

public class MyHandler implements AuthenticationSuccessHandler {
    private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();

    public void onAuthenticationSuccess(HttpServletRequest request,
        HttpServletResponse response, Authentication auth) {
        if (hasTemporaryPassword(auth)) {
            response.sendRedirect("/changePassword");
        } else {
            target.onAuthenticationSuccess(request, response, auth);
        }
    }

    public void proceed(HttpServletRequest request, 
        HttpServletResponse response, Authentication auth) {
        target.onAuthenticationSuccess(request, response, auth);
    }
}

@Controller("/changePassword")
public class ChangePasswordController {

    @Autowired
    private MyHandler handler;

    @RequestMapping(method = POST)
    public void changePassword(HttpServletRequest request, 
        HttpServletResponse response,
        @RequestParam(name = "newPassword") String newPassword) {

        // handle password change
        ...

        // proceed to the secured page
        handler.proceed(request, response, auth);        
    }

    // form display method, etc
    ...
}
axtavt
Thanks for this. I can do the first part pretty easily but not sure what you mean by "redirect user to...using SavedRequestAwareAuthenticationSuccessHandler". How do I redirect to a handler?
drewzilla
@dewzilla: I added the sample of how it might look like (with Spring MVC controller for password change, not tested).
axtavt
A: 

Yes, I did this with a filter ForceChangePasswordFilter. Because if the user types the url by hand they can bypass the change password form. With the filter the request always get intercepted.

rodrigoap