Spring Security如何修改响应HTTP状态码?授权失败需返回401
修改Spring Security授权失败时的HTTP 401状态码方案
针对你当前的Spring Security配置场景,要实现授权失败(包括未认证访问受保护资源、已认证但权限不足)时返回HTTP 401状态码,可以通过以下两种核心方式调整,结合你的现有代码来修改:
1. 处理未认证请求:自定义AuthenticationEntryPoint
默认情况下,未登录用户访问受保护资源会被跳转到登录页,我们可以自定义AuthenticationEntryPoint来直接返回401状态码:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(ADMIN_MATCHERS).access("hasRole('ADMIN')") .anyRequest().authenticated() .and() .formLogin() .usernameParameter(USERNAME) .passwordParameter(PASSWORD) .loginPage(ADMIN_LOGIN) .permitAll() .loginProcessingUrl("/admin/login") // 补充完整你的登录处理接口地址 .and() // 新增:自定义未认证时的响应逻辑 .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); // 若需要返回JSON格式响应,可添加以下配置 response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write("{\"message\": \"未授权访问,请先登录\"}"); }); }
2. 处理权限不足请求:自定义AccessDeniedHandler
如果希望已登录但无对应角色(比如非ADMIN用户访问ADMIN_MATCHERS)时也返回401(默认是403 Forbidden),可以再添加AccessDeniedHandler:
@Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(ADMIN_MATCHERS).access("hasRole('ADMIN')") .anyRequest().authenticated() .and() .formLogin() .usernameParameter(USERNAME) .passwordParameter(PASSWORD) .loginPage(ADMIN_LOGIN) .permitAll() .loginProcessingUrl("/admin/login") .and() .exceptionHandling() .authenticationEntryPoint((request, response, authException) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write("{\"message\": \"未授权访问,请先登录\"}"); }) // 新增:处理权限不足的情况,返回401 .accessDeniedHandler((request, response, accessDeniedException) -> { response.setStatus(HttpStatus.UNAUTHORIZED.value()); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.getWriter().write("{\"message\": \"权限不足,无法访问该资源\"}"); }); }
补充说明
- 如果你只需要未认证场景返回401,权限不足保持默认403,仅添加
authenticationEntryPoint即可。 - 可以根据业务需求调整响应内容,比如返回纯文本、JSON结构或者自定义错误信息。
- 注意确保
loginProcessingUrl的地址与你的前端登录请求地址一致,否则登录逻辑会失效。
内容的提问来源于stack exchange,提问作者Вячеслав Чернышов
相关产品推荐
相关产品推荐

