/springboot-security
Spring Boot 服务的身份验证/授权、校验、CSRF、机密管理、响应头、速率限制及依赖安全的 Spring Security 最佳实践。
$ npx -y skills add xu-xiang/everything-claude-code-zh --skill springboot-security --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
- You can call itInvoke it directly when you want it.
- Slash command
/springboot-security
Context preview
The summary Claude sees to decide when to auto-load this skill.
Spring Boot 服务的身份验证/授权、校验、CSRF、机密管理、响应头、速率限制及依赖安全的 Spring Security 最佳实践。
SKILL.md
springboot-security.SKILL.mdname: springboot-security
description: Spring Boot 服务的身份验证/授权、校验、CSRF、机密管理、响应头、速率限制及依赖安全的 Spring Security 最佳实践。
origin: ECC
Spring Boot 安全审查(Security Review)
在添加身份验证(Auth)、处理输入、创建端点或处理机密信息时使用。
何时激活(When to Activate)
- 添加身份验证(JWT、OAuth2、基于 Session 的认证)
- 实现授权(`@PreAuthorize`、基于角色的访问控制)
- 校验用户输入(Bean Validation、自定义校验器)
- 配置 CORS、CSRF 或安全响应头
- 管理机密信息(Vault、环境变量)
- 添加速率限制(Rate Limiting)或暴力破解防护
- 扫描依赖项的 CVE 漏洞
身份验证(Authentication)
- 优先使用无状态 JWT 或带撤回列表的模糊令牌(Opaque Tokens)
- 为 Session 使用 `httpOnly`、`Secure`、`SameSite=Strict` 属性的 Cookie
- 使用 `OncePerRequestFilter` 或资源服务器校验令牌
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
Authentication auth = jwtService.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}授权(Authorization)
- 启用方法安全:`@EnableMethodSecurity`
- 使用 `@PreAuthorize("hasRole('ADMIN')")` 或 `@PreAuthorize("@authz.canEdit(#id)")`
- 默认拒绝访问(Deny by default);仅公开所需的权限范围(Scopes)
@RestController
@RequestMapping("/api/admin")
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/users")
public List<UserDto> listUsers() {
return userService.findAll();
}
@PreAuthorize("@authz.isOwner(#id, authentication)")
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}输入校验(Input Validation)
- 在控制器(Controllers)上对 `@Valid` 使用 Bean Validation
- 在 DTO 上应用约束:`@NotBlank`、`@Email`、`@Size`、自定义校验器
- 在渲染前,使用白名单清理(Sanitize)任何 HTML 内容
// 差(BAD):没有校验
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
return userService.create(dto);
}
// 好(GOOD):校验过的 DTO
public record CreateUserDto(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email,
@NotNull @Min(0) @Max(150) Integer age
) {}
@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.create(dto));
}防止 SQL 注入(SQL Injection Prevention)
- 使用 Spring Data 存储库(Repositories)或参数化查询
- 对于原生查询(Native Queries),使用 `:param` 绑定;切勿拼接字符串
// 差(BAD):在原生查询中直接拼接字符串
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
// 好(GOOD):参数化原生查询
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);
// 好(GOOD):Spring Data 衍生查询(自动参数化)
List<User> findByEmailAndActiveTrue(String email);密码编码(Password Encoding)
- 始终使用 BCrypt 或 Argon2 对密码进行哈希处理 —— 严禁存储明文
- 使用 `PasswordEncoder` Bean,而不是手动执行哈希
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // 成本因子(cost factor)为 12
}
// 在 Service 中
public User register(CreateUserDto dto) {
String hashedPassword = passwordEncoder.encode(dto.password());
return userRepository.save(new User(dto.email(), hashedPassword));
}CSRF 防护(CSRF Protection)
- 对于基于浏览器会话(Session)的应用,保持 CSRF 启用;在表单/请求头中包含令牌
- 对于使用 Bearer 令牌的纯 API,禁用 CSRF 并依赖无状态身份验证
http
.csrf(csrf -> csrf.disable())
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
机密管理(Secrets Management)
- 源代码中不保留机密;从环境变量或 Vault 加载
- 保持 `application.yml` 不含凭据信息;使用占位符
- 定期轮换令牌和数据库凭据
# 差(BAD):在 application.yml 中硬编码
spring:
datasource:
password: mySecretPassword123
# 好(GOOD):使用环境变量占位符
spring:
datasource:
password: ${DB_PASSWORD}
# 好(GOOD):Spring Cloud Vault 集成
spring:
cloud:
vault:
uri: https://vault.example.com
token: ${VAULT_TOKEN}安全响应头(Security Headers)
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.xssProtection(Customizer.withDefaults())
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));CORS 配置
- 在安全过滤器(Security Filter)级别配置 CORS,而不是按控制器配置
- 限制允许的源(Origins) —— 在生产环境中严禁使用 `*`
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
// 在 SecurityFilterChain 中:
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));速率限制(Rate Limiting)
- 在高开销端点上应用 Bucket4j 或网关级限制
- 对爆发性请求进行日志记录和告警;返回 429 错误并提供重试提示
// 使用 Bucket4j 进行单端点速率限制
@Component
public class RateLimitFilter extends OncePerRequestFilter {
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
private Bucket createBucket() {
return Bucket.builder()
.addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
.build();
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String clientIp = request.getRemoteAddr();Read more
name: springboot-security description: Spring Boot 服务的身份验证/授权、校验、CSRF、机密管理、响应头、速率限制及依赖安全的 Spring Security 最佳实践。 origin: ECC
Spring Boot 安全审查(Security Review)
在添加身份验证(Auth)、处理输入、创建端点或处理机密信息时使用。
何时激活(When to Activate)
- 添加身份验证(JWT、OAuth2、基于 Session 的认证)
- 实现授权(`@PreAuthorize`、基于角色的访问控制)
- 校验用户输入(Bean Validation、自定义校验器)
- 配置 CORS、CSRF 或安全响应头
- 管理机密信息(Vault、环境变量)
- 添加速率限制(Rate Limiting)或暴力破解防护
- 扫描依赖项的 CVE 漏洞
身份验证(Authentication)
- 优先使用无状态 JWT 或带撤回列表的模糊令牌(Opaque Tokens)
- 为 Session 使用 `httpOnly`、`Secure`、`SameSite=Strict` 属性的 Cookie
- 使用 `OncePerRequestFilter` 或资源服务器校验令牌
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith("Bearer ")) {
String token = header.substring(7);
Authentication auth = jwtService.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
}
chain.doFilter(request, response);
}
}授权(Authorization)
- 启用方法安全:`@EnableMethodSecurity`
- 使用 `@PreAuthorize("hasRole('ADMIN')")` 或 `@PreAuthorize("@authz.canEdit(#id)")`
- 默认拒绝访问(Deny by default);仅公开所需的权限范围(Scopes)
@RestController
@RequestMapping("/api/admin")
public class AdminController {
@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/users")
public List<UserDto> listUsers() {
return userService.findAll();
}
@PreAuthorize("@authz.isOwner(#id, authentication)")
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
userService.delete(id);
return ResponseEntity.noContent().build();
}
}输入校验(Input Validation)
- 在控制器(Controllers)上对 `@Valid` 使用 Bean Validation
- 在 DTO 上应用约束:`@NotBlank`、`@Email`、`@Size`、自定义校验器
- 在渲染前,使用白名单清理(Sanitize)任何 HTML 内容
// 差(BAD):没有校验
@PostMapping("/users")
public User createUser(@RequestBody UserDto dto) {
return userService.create(dto);
}
// 好(GOOD):校验过的 DTO
public record CreateUserDto(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email String email,
@NotNull @Min(0) @Max(150) Integer age
) {}
@PostMapping("/users")
public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserDto dto) {
return ResponseEntity.status(HttpStatus.CREATED)
.body(userService.create(dto));
}防止 SQL 注入(SQL Injection Prevention)
- 使用 Spring Data 存储库(Repositories)或参数化查询
- 对于原生查询(Native Queries),使用 `:param` 绑定;切勿拼接字符串
// 差(BAD):在原生查询中直接拼接字符串
@Query(value = "SELECT * FROM users WHERE name = '" + name + "'", nativeQuery = true)
// 好(GOOD):参数化原生查询
@Query(value = "SELECT * FROM users WHERE name = :name", nativeQuery = true)
List<User> findByName(@Param("name") String name);
// 好(GOOD):Spring Data 衍生查询(自动参数化)
List<User> findByEmailAndActiveTrue(String email);密码编码(Password Encoding)
- 始终使用 BCrypt 或 Argon2 对密码进行哈希处理 —— 严禁存储明文
- 使用 `PasswordEncoder` Bean,而不是手动执行哈希
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12); // 成本因子(cost factor)为 12
}
// 在 Service 中
public User register(CreateUserDto dto) {
String hashedPassword = passwordEncoder.encode(dto.password());
return userRepository.save(new User(dto.email(), hashedPassword));
}CSRF 防护(CSRF Protection)
- 对于基于浏览器会话(Session)的应用,保持 CSRF 启用;在表单/请求头中包含令牌
- 对于使用 Bearer 令牌的纯 API,禁用 CSRF 并依赖无状态身份验证
http .csrf(csrf -> csrf.disable()) .sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
机密管理(Secrets Management)
- 源代码中不保留机密;从环境变量或 Vault 加载
- 保持 `application.yml` 不含凭据信息;使用占位符
- 定期轮换令牌和数据库凭据
# 差(BAD):在 application.yml 中硬编码
spring:
datasource:
password: mySecretPassword123
# 好(GOOD):使用环境变量占位符
spring:
datasource:
password: ${DB_PASSWORD}
# 好(GOOD):Spring Cloud Vault 集成
spring:
cloud:
vault:
uri: https://vault.example.com
token: ${VAULT_TOKEN}安全响应头(Security Headers)
http
.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'"))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::sameOrigin)
.xssProtection(Customizer.withDefaults())
.referrerPolicy(rp -> rp.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.NO_REFERRER)));CORS 配置
- 在安全过滤器(Security Filter)级别配置 CORS,而不是按控制器配置
- 限制允许的源(Origins) —— 在生产环境中严禁使用 `*`
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(true);
config.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}
// 在 SecurityFilterChain 中:
http.cors(cors -> cors.configurationSource(corsConfigurationSource()));速率限制(Rate Limiting)
- 在高开销端点上应用 Bucket4j 或网关级限制
- 对爆发性请求进行日志记录和告警;返回 429 错误并提供重试提示
// 使用 Bucket4j 进行单端点速率限制
@Component
public class RateLimitFilter extends OncePerRequestFilter {
private final Map<String, Bucket> buckets = new ConcurrentHashMap<>();
private Bucket createBucket() {
return Bucket.builder()
.addLimit(Bandwidth.classic(100, Refill.intervally(100, Duration.ofMinutes(1))))
.build();
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String clientIp = request.getRemoteAddr();🌐 Language / 语言 / 語言 为 AI 智能体(Agent)框架打造的性能优化系统。源自 Anthropic 黑客松获胜作品。 这不仅仅是配置文件。它是一个完整的系统:包含技能(Skills)、本能(Instincts)、内存优化、持续学习、安全扫描以及研究优先的开发模式。这些生产级的智能体(Agents)、钩子(Hooks)、命令(Commands)、规则(Rules)以及 MCP 配置,是在构建真实产品的 10 个多月高强度日常使用中演化而来的。 适用于 Claude Code, Codex,
Repo: xu-xiang/everything-claude-code-zh
Other skills on everything-claude-code.
- /oneskill
发现技能(Skill),迭代查询,并在任何环境中自动安装技能。
Open skill - /api-design
生产级 API 的 REST API 设计模式,包括资源命名、状态码、分页、过滤、错误响应、版本控制和速率限制。
Open skill - /article-writing
编写文章、指南、博客帖子、教程、新闻通讯(newsletter)以及其他长篇内容。这些内容具有从提供的示例或品牌指南中提取出的独特语气。当用户需要比段落更长的精美文案,且对语气一致性、结构和可信度有要求时,请使用此技能(Skill)。
Open skill - /autonomous-loops
自主运行 Claude Code 循环的模式与架构 —— 从简单的顺序流水线到 RFC 驱动的多智能体 DAG 系统。
Open skill - /backend-patterns
后端架构模式、API 设计、数据库优化以及针对 Node.js、Express 和 Next.js API 路由的服务端最佳实践。
Open skill - /clickhouse-io
ClickHouse 数据库模式、查询优化、分析以及高性能分析负载的数据工程最佳实践。
Open skill

