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