|
| 1 | +package org.baeldung.security; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | + |
| 5 | +import javax.servlet.ServletException; |
| 6 | +import javax.servlet.http.HttpServletRequest; |
| 7 | +import javax.servlet.http.HttpServletResponse; |
| 8 | +import javax.servlet.http.HttpSession; |
| 9 | + |
| 10 | +import org.springframework.security.core.Authentication; |
| 11 | +import org.springframework.security.web.WebAttributes; |
| 12 | +import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler; |
| 13 | +import org.springframework.security.web.authentication.AuthenticationSuccessHandler; |
| 14 | + |
| 15 | +/** |
| 16 | + * <tt>AuthenticationSuccessHandler</tt> which can be configured with a default URL which users should be |
| 17 | + * sent to upon successful authentication. |
| 18 | + * <p> |
| 19 | + * The logic used is that of the {@link AbstractAuthenticationTargetUrlRequestHandler parent class}. |
| 20 | + * |
| 21 | + * @author Luke Taylor |
| 22 | + * @since 3.0 |
| 23 | + */ |
| 24 | +public class MySimpleUrlAuthenticationSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements AuthenticationSuccessHandler { |
| 25 | + |
| 26 | + public MySimpleUrlAuthenticationSuccessHandler() { |
| 27 | + super(); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Constructor which sets the <tt>defaultTargetUrl</tt> property of the base class. |
| 32 | + * @param defaultTargetUrl the URL to which the user should be redirected on successful authentication. |
| 33 | + */ |
| 34 | + public MySimpleUrlAuthenticationSuccessHandler(final String defaultTargetUrl) { |
| 35 | + setDefaultTargetUrl(defaultTargetUrl); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Calls the parent class {@code handle()} method to forward or redirect to the target URL, and |
| 40 | + * then calls {@code clearAuthenticationAttributes()} to remove any leftover session data. |
| 41 | + */ |
| 42 | + @Override |
| 43 | + public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException { |
| 44 | + handle(request, response, authentication); |
| 45 | + clearAuthenticationAttributes(request); |
| 46 | + } |
| 47 | + |
| 48 | + /** |
| 49 | + * Removes temporary authentication-related data which may have been stored in the session |
| 50 | + * during the authentication process. |
| 51 | + */ |
| 52 | + protected final void clearAuthenticationAttributes(final HttpServletRequest request) { |
| 53 | + final HttpSession session = request.getSession(false); |
| 54 | + |
| 55 | + if (session == null) { |
| 56 | + return; |
| 57 | + } |
| 58 | + |
| 59 | + session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments