我遇到了问题。默认情况下,身份验证后的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。
基本上:
/protected
/login
页面/protected
如何使用自定义successHandler进行操作?
答案 0 :(得分:2)
在我的项目中,我使用DefaultSavedRequest
完成了我的要求。 AbstractAuthenticationProcessingFilter和SavedRequestAwareWrapper使用DefaultSavedRequest
类在成功验证后重现请求。 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;
}
}
答案 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)
}
}