gpt4 book ai didi

java - 没有重定向的 Spring Security

转载 作者:搜寻专家 更新时间:2023-11-01 03:04:45 24 4
gpt4 key购买 nike

我有一个无状态的 Spring Security 实现,它使用基于 token 的身份验证。我的大部分逻辑都位于扩展 AbstractAuthenticationProcessingFilter 的类中。我的问题是,身份验证成功后,AbstractAuthenticationProcessingFilter 进行了 302 重定向,这是我不想要的。我只想完成原始请求。我该如何解决这个问题?

最佳答案

通过覆盖成功和失败处理程序,我能够使 spring security 公开的“登录”rest 方法返回“200 OK”而不是“302 重定向”。下面的代码显示了如何实现相同的目的。

        //configure http by using the successHandler 
//and failure handler methods
http.
formLogin()
.loginPage("/authentication/login")
.loginProcessingUrl("/authentication/processLogin")
.successHandler(successHandler())
.failureHandler(failureHandler())
.and()
......



private AuthenticationFailureHandler failureHandler() {
return new SimpleUrlAuthenticationFailureHandler() {
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication Failed. Wrong username or password or both");
}
};
}


private AuthenticationSuccessHandler successHandler() {
return new SimpleUrlAuthenticationSuccessHandler() {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
session.setMaxInactiveInterval(60*180);
response.getWriter().println("LoginSuccessful");
}
};
}

关于java - 没有重定向的 Spring Security,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26554664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com