小编典典

Spring Security匿名401而不是403

spring-boot

我在Spring安全中的默认行为有一个问题,它带有Java Config提供的授权请求。

http
       ....
       .authorizeRequests()
          .antMatchers("/api/test/secured/*").authenticated()

例如,当我拨打电话/api/test/secured/user而没有登录(使用匿名用户)时,它将返回403
Forbidden。当匿名用户希望获得资源authenticated()@PreAuthorize资源的安全保护时,是否有一种简单的方法可以将状态更改为“
401未经授权” ?


阅读 582

收藏
2020-05-30

共1个答案

小编典典

我在这里有解决方案:

http
   .authenticationEntryPoint(authenticationEntryPoint)

AuthenticationEntryPoint源代码:

@Component
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {

    private final Logger log = LoggerFactory.getLogger(Http401UnauthorizedEntryPoint.class);

    /**
     * Always returns a 401 error code to the client.
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
            ServletException {

        log.debug("Pre-authenticated entry point called. Rejecting access");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
    }
}
2020-05-30