默认情况下,身份验证后的Spring安全将您重定向到您之前尝试访问的受保护页面。
当我实现自己的成功处理程序时
@Component class MyS: AuthenticationSuccessHandler { override fun onAuthenticationSuccess(request: HttpServletRequest?, response: HttpServletResponse?, authentication: Authentication?) { response?.sendRedirect(request?.getHeader(HttpHeaders.REFERER)) } }
class SecurityConfigTH(@Autowired private val myHandler: MyS) : WebSecurityConfigurerAdapter() { ... .formLogin() .loginPage("/en/login") .successHandler(myHandler) .permitAll() }
我无法达到同样的效果。我尝试将重定向到引荐来源网址,但在这种情况下,引荐来源网址为/ en / login页面。
基本上:
/protected
/login
如何使用自定义successHandler做到这一点?
在我的项目中,我用DefaultSavedRequest它满足了我的要求。DefaultSavedRequest成功认证后,AbstractAuthenticationProcessingFilter和SavedRequestAwareWrapper使用该类重现请求。ExceptionTranslationFilter在身份验证异常时存储此类的实例。
DefaultSavedRequest
https://docs.spring.io/spring- security/site/docs/4.1.2.RELEASE/apidocs/org/springframework/security/web/savedrequest/DefaultSavedRequest.html
@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST"); if(defaultSavedRequest != null){ String targetURL = defaultSavedRequest.getRedirectUrl(); redirectStrategy.sendRedirect(request, response, targetURL); return; } }