身份认证与应用安全 / 系统课时

统一返回 401 与 403

统一返回 401 与 403

前后端分离接口不能把所有鉴权失败都返回成同一种错误。Spring Security 可以分别用 AuthenticationEntryPoint 处理“还没有认证”,用 AccessDeniedHandler 处理“已经认证但权限不足”,从而让前端可靠地区分重新登录与无权访问。

学习目标

  • 准确区分 HTTP 401 与 403 在请求鉴权中的含义
  • 配置统一 JSON 格式的 AuthenticationEntryPoint 和 AccessDeniedHandler
  • 用未认证请求与低权限 JWT 分别验证两条失败路径

先区分未认证和无权限

访问受保护资源时,没有可用认证身份的请求应进入 AuthenticationEntryPoint,返回 401;已经存在认证身份,但授权规则不允许访问时,应进入 AccessDeniedHandler,返回 403。两者的前端动作通常不同:401 往往触发重新认证,403 则表示当前账号即使已登录也没有该资源权限。

Spring Security 401 与 403 分流

配置统一 JSON 错误体

下面是可直接放进 Spring Boot 项目的完整配置类。示例把 /api/auth/** 放行,把 /api/admin/** 限制为 ROLE_ADMIN,其余接口要求已认证。

java
package com.example.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint(new JsonAuthenticationEntryPoint())
                .accessDeniedHandler(new JsonAccessDeniedHandler()));

        return http.build();
    }

    static final class JsonAuthenticationEntryPoint
            implements AuthenticationEntryPoint {
        @Override
        public void commence(
                HttpServletRequest request,
                HttpServletResponse response,
                AuthenticationException exception) throws IOException {
            writeJson(
                    response,
                    HttpServletResponse.SC_UNAUTHORIZED,
                    "UNAUTHORIZED",
                    "Authentication required");
        }
    }

    static final class JsonAccessDeniedHandler
            implements AccessDeniedHandler {
        @Override
        public void handle(
                HttpServletRequest request,
                HttpServletResponse response,
                AccessDeniedException exception) throws IOException {
            writeJson(
                    response,
                    HttpServletResponse.SC_FORBIDDEN,
                    "FORBIDDEN",
                    "Access denied");
        }
    }

    private static void writeJson(
            HttpServletResponse response,
            int status,
            String code,
            String message) throws IOException {
        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().write(
                "{\"code\":\"" + code + "\",\"message\":\"" + message + "\"}");
    }
}

hasRole("ADMIN") 会检查 ROLE_ADMIN 权限,因此 JWT 转换出的 GrantedAuthority 命名必须与授权规则一致。若项目统一使用 ADMIN、order:read 这类原始权限名,应改用 hasAuthority(...),不要在角色前缀上混用两套约定。

验证两条失败路径

下面的验证依赖项目已有 JWT 认证链,并准备一个不含 ROLE_ADMIN 的有效令牌。<PORT> 与 <TOKEN_WITHOUT_ADMIN> 的实际值可能不同。

bash
curl -s -o /tmp/unauthorized.json -w "%{http_code}\n" \
  http://localhost:<PORT>/api/admin/report
cat /tmp/unauthorized.json

curl -s -o /tmp/forbidden.json -w "%{http_code}\n" \
  -H "Authorization: Bearer <TOKEN_WITHOUT_ADMIN>" \
  http://localhost:<PORT>/api/admin/report
cat /tmp/forbidden.json

预期输出

text
401
{"code":"UNAUTHORIZED","message":"Authentication required"}
403
{"code":"FORBIDDEN","message":"Access denied"}

第一组请求没有认证身份,因此返回 401;第二组请求已经通过 JWT 认证,但缺少 ROLE_ADMIN,因此返回 403。若第二组也得到 401,应先确认 JWT 过滤器是否成功把 Authentication 写入 SecurityContext;若未认证请求却得到 403,则应检查是否绕过了 Spring Security 的异常处理链,或业务代码是否自行写死了状态码。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

统一返回 401 与 403

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通