Spring Security匿名401而不是403 [英] Spring Security anonymous 401 instead of 403

查看:1379
本文介绍了Spring Security匿名401而不是403的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了Spring安全性中的默认行为问题,并且Java Config提供了授权请求。

I have a problem with default behaviour in spring security with authorize requests provided with Java Config.

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

当我打电话给例如 / api / test / secured / user 没有登录(使用匿名用户),它返回403 Forbidden。当匿名用户希望通过 authenticated() @PreAuthorize 资源?

When I do a call to for example /api/test/secured/user without login (with anonymous user), it returns 403 Forbidden. Is there an easy way to change status to 401 Unauthorized when anonymous user wants to get secured by authenticated() or @PreAuthorize resource?

推荐答案

我有解决方案这里

http
   .authenticationEntryPoint(authenticationEntryPoint)

AuthenticationEntryPoint源代码:

AuthenticationEntryPoint source code:

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

这篇关于Spring Security匿名401而不是403的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆