身份认证与应用安全 / 系统课时
准备受保护的测试接口
准备受保护的测试接口
JWT 过滤器真正接入前,先准备一组不会变化的测试目标:一个任何人都能访问的接口,以及一个只有认证成功后才能进入的接口。这样后续出现 401、过滤器未生效或权限规则异常时,可以快速判断问题发生在哪一层。
学习目标
- 准备匿名接口与受保护接口,形成固定的鉴权测试基线。
- 用
SecurityFilterChain明确哪些路径放行、哪些路径必须认证。 - 通过状态码验证当前安全边界,并区分未认证与业务代码问题。
固定两类测试目标
测试接口不承担真实业务,重点是路径稳定、返回简单。建议把匿名接口放在 /api/public/**,把需要登录的接口放在 /api/protected/**,后续 JWT 过滤器只要围绕这两个目标验证即可。
| 路径 | 访问要求 | 当前用途 |
|---|---|---|
GET /api/public/ping |
匿名允许 | 证明应用和公开路由正常 |
GET /api/protected/profile |
必须认证 | 验证过滤链是否建立认证身份 |
这种安排能把“接口本身坏了”和“安全链拦截了”分开:公开接口也失败时先查 Web 层;公开接口成功而受保护接口返回 401 时,再查认证链。
实现测试控制器
下面是片段示例,放入已有的 Spring Boot Web 项目。受保护接口读取 Authentication,因此后续只要 JWT 过滤器成功写入认证上下文,就能直接看到当前用户名。
package com.example.auth.api;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class TestApiController {
@GetMapping("/public/ping")
public Map<String, String> ping() {
return Map.of("message", "pong");
}
@GetMapping("/protected/profile")
public Map<String, String> profile(Authentication authentication) {
return Map.of(
"message", "protected-ok",
"user", authentication.getName()
);
}
}当前还没有 JWT 认证时,请求不会进入 profile 方法,因此 authentication 不会出现空值调用问题;安全过滤链会先拦截未认证请求。
配置访问边界
下面同样是片段示例,要求项目已经引入 Spring Security。公开路径使用 permitAll(),受保护路径使用 authenticated();其他未声明路径直接拒绝,能减少测试阶段的意外放行。
package com.example.auth.config;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/public/**").permitAll()
.requestMatchers("/api/protected/**").authenticated()
.anyRequest().denyAll()
)
.exceptionHandling(exceptions -> exceptions
.authenticationEntryPoint((request, response, exception) ->
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED))
);
return http.build();
}
}这里暂时只验证 GET 接口,所以不需要为了本课额外修改 CSRF 策略。后续实现 JSON 登录和无状态 JWT 时,再根据实际认证方式统一处理相关安全配置,避免在测试基线里混入无关变量。
运行并验证状态码
启动应用后,用同一组命令检查两个固定目标。<PORT> 替换为应用实际端口。
public_status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:<PORT>/api/public/ping)
protected_status=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:<PORT>/api/protected/profile)
echo "public=$public_status"
echo "protected=$protected_status"预期输出
public=200
protected=401此时 401 是预期基线:请求尚未建立认证身份。后续加入 JWT 过滤器后,公开接口仍应保持 200,而携带有效令牌访问受保护接口应从 401 变为 200。如果用户已经认证但缺少某项授权,才应进一步用 403 表达“已认证但无权限”,不要把两种情况混在一起。