我在Spring安全中的默认行为有一个问题,它带有Java Config提供的授权请求。
http .... .authorizeRequests() .antMatchers("/api/test/secured/*").authenticated()
例如,当我拨打电话/api/test/secured/user而没有登录(使用匿名用户)时,它将返回403 Forbidden。当匿名用户希望获得资源authenticated()或@PreAuthorize资源的安全保护时,是否有一种简单的方法可以将状态更改为“ 401未经授权” ?
/api/test/secured/user
authenticated()
@PreAuthorize
我在这里有解决方案:
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"); } }