春季安全。身份验证后重定向到受保护的页面

时间:2017-10-16 16:03:10

标签: java spring spring-boot spring-security kotlin

我遇到了问题。默认情况下,身份验证后的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()
 }

我无法达到同样的效果。我尝试重定向到referrer,但在这种情况下,referrer是/ en / login page。

基本上:

  1. 用户尝试访问受保护的网址/protected
  2. 将用户重定向到/login页面
  3. 验证后,应将用户重定向到/protected
  4. 如何使用自定义successHandler进行操作?

2 个答案:

答案 0 :(得分:2)

在我的项目中,我使用DefaultSavedRequest完成了我的要求。 AbstractAuthenticationProcessingFilter和SavedRequestAwareWrapper使用DefaultSavedRequest类在成功验证后重现请求。 ExceptionTranslationFilter在验证异常时存储此类的实例。

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;
    }
}

答案 1 :(得分:0)

感谢Mhod的回答,这就行了。

@Component
class MyS: AuthenticationSuccessHandler {
    override fun onAuthenticationSuccess(request: HttpServletRequest?, response: HttpServletResponse?, authentication: Authentication?) {

        val defaultSavedRequest = request?.session?.getAttribute("SPRING_SECURITY_SAVED_REQUEST") as DefaultSavedRequest
        response?.sendRedirect(defaultSavedRequest.requestURI)

    }
}