AuthenticationEntryPoint

AuthenticationEntryPoint

我对Java Config随附的授权请求的 Spring 安全性中的默认行为有疑问。

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

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

最佳答案

我有解决方案here:

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");
    }
}

10-08 18:34