身份验证后重定向到受保护的页面 [英] Redirect to protected page after authentication

查看:163
本文介绍了身份验证后重定向到受保护的页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,身份验证后的春季安全性会将您重定向到您之前尝试访问的受保护页面.

By default, spring security after authentication redirects you to protected page you tried to access before.

当我实现自己的成功处理程序时

When I implement my own success handler

@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页面.

I cannot achieve the same effect. I tried redirect to referrer, but in this case referrer is /en/login page.

基本上:

  1. 用户尝试访问受保护的URL /protected
  2. 将用户重定向到/login页面
  3. 身份验证后,用户应再次重定向到/protected
  1. User try to access protected url /protected
  2. Redirect user to /login page
  3. After authentication user should be redirected to /protected again

如何使用自定义的successHandler进行操作?

How to do it with custom successHandler?

推荐答案

在我的项目中,我使用DefaultSavedRequest满足了我的要求.成功通过身份验证后,AbstractAuthenticationProcessingFilter和SavedRequestAwareWrapper使用DefaultSavedRequest类来重现请求. ExceptionTranslationFilter在身份验证异常时存储此类的实例.

In my project, i used DefaultSavedRequest that completed my requirement. DefaultSavedRequest class is used by AbstractAuthenticationProcessingFilter and SavedRequestAwareWrapper to reproduce the request after successful authentication. An instance of this class is stored at the time of an authentication exception by 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;
    }
}

这篇关于身份验证后重定向到受保护的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆