我正在使用 Spring boot 2.2.9,但在获取 401 HTTP 错误的入口点时遇到问题,我正在尝试更改响应的行为,就像我们可以使用 spring 错误处理程序(ResponseEntityExceptionHandler 类)为其他 http 错误 谢谢
答案 0 :(得分:2)
将您的 Spring Boot 版本更新为 1.3.0.RELEASE,您将获得
<块引用>Http401AuthenticationEntryPoint
免费。在您的安全配置中配置身份验证入口点,如下所示:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(PROTECTED_RESOURCES)
.hasRole("USER")
.anyRequest()
.permitAll()
.and()
.anonymous().disable()
.exceptionHandling()
.authenticationEntryPoint(new org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint("headerValue"));
}
并且 Spring Boot 将返回 HTTP 401:
状态代码:401 未经授权 缓存控制:无缓存,无存储,max-age=0,必须重新验证 过期时间:0 编译指示:无缓存 服务器:Apache-Coyote/1.1 传输编码:分块 WWW-Authenticate: headerValue X-Content-Type-Options: nosniff x-xss-保护:1;模式=块
答案 1 :(得分:0)
回答这个问题: 2021 年春季安全版本 5.x.x。 如果您没有使用 BasicAuthenticationFilter 或 AbstractAuthenticationFilter 并且正在使用您自己的自定义过滤器进行身份验证而不提供任何 AuthenticationEntryPoint 并且您像我一样认为未经身份验证的用户将通过 ExeptionTranslatorFilter 由 Spring Security 自动处理,那么您会感到沮丧我。 这个答案对我有帮助,但链接不起作用,所以这里是当前版本官方文档的更新链接,清楚地提到了这一点authenticationEntryPont 所以我们需要添加到配置中:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity (prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new MyAuthenticationEntryPoint());
}
}
然后我们实现这个类
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
// 401
}