我正在使用Spring Security的基本授权。我通过Java配置配置后者。
我想向客户端发送HTTP 401错误代码,其中包含消息"无效的登录名和密码"如果它们无效。但是,目前Spring Security只显示一个默认的弹出窗口。
这是我的Spring安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated().and()
.httpBasic()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/pages/index.html");
http.exceptionHandling().authenticationEntryPoint(new AjaxAuthorizationPoint());
}
据我所知,我必须添加自定义authentificationEntryPoint
来处理无效凭据的情况,即我必须向其发送包含错误消息的401错误代码
这是代码。为简单起见,该方法的主体相当简单。
public class AjaxAuthorizationPoint extends BasicAuthenticationEntryPoint{
@Override
public void commence(final HttpServletRequest request,
final HttpServletResponse response,
final AuthenticationException authException) throws IOException {
System.out.println("blah");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
然而,方法public void commence()
没有启动,当我输入无效的登录名和密码时,Spring只是向我发送默认的登录弹出窗口。
如何重新定义默认策略?如何配置Spring安全性以发送HTTP 401错误代码而不是显示默认登录页面?
答案 0 :(得分:1)
我想,我找到了解决问题的方法。这里的代码完全符合我的需要。
Spring安全配置:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().authenticationEntryPoint(new AjaxAuthorizationPoint("/ajax_login"));
http.authorizeRequests().anyRequest().authenticated().and().httpBasic()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/pages/index.html");
}
自定义ajax授权点:
public class AjaxAuthorizationPoint extends LoginUrlAuthenticationEntryPoint {
public AjaxAuthorizationPoint(String loginFormUrl) {
super(loginFormUrl);
}
@Override
public void commence(HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setStatus(403);
response.getWriter().print("Invalid login/password");
response.getWriter().flush();
}
}
非常感谢任何代码审核。