身份验证后重定向到受保护的页面 [英] Redirect to protected page after authentication
问题描述
默认情况下,身份验证后的春季安全性会将您重定向到您之前尝试访问的受保护页面.
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.
基本上:
- 用户尝试访问受保护的URL
/protected
- 将用户重定向到
/login
页面 - 身份验证后,用户应再次重定向到
/protected
- User try to access protected url
/protected
- Redirect user to
/login
page - 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.
@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屋!