Token导航 LogoToken导航

Agent Skill · 开发

spring-boot-security-jwt(spring boot 安全 JWT)

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

spring-boot-security-jwt 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描有提醒项,按安装量在开发类的 21,746 个 Skill 里排第 2,105。

总安装 20,468周安装 828GitHub Stars 229下载 6,425核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-boot-security-jwt(spring boot 安全 JWT)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/spring-boot-security-jwt
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-security-jwt
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-security-jwt

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

Spring Boot 3.5.x 的 JWT 身份验证和授权,具有令牌生成、刷新策略和基于角色/权限的访问控制。

涵盖使用 JJWT 生成令牌、Bearer/cookie 身份验证以及使用 Spring Security 6.x 的无状态会话管理 支持数据库支持和 OAuth2 提供商集成(Google、GitHub)与现代 SecurityFilterChain 配置 包括刷新令牌轮换、令牌黑名单和用于生产安全的密钥轮换策略 通过自定义权限评估器和 @PreAuthorize 提供基于角色 (RBAC) 和基于权限的访问控制模式 注释 实现 JWT 过滤器、身份验证端点和用于安全验证的全面测试模式

来源仓库内路径:skills/spring-boot-security-jwt

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill sp…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

spring-boot-security-jwt 怎么安装?

在终端执行 npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

spring-boot-security-jwt 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

spring-boot-security-jwt 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

spring-boot-security-jwt 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

spring-boot-security-jwt 用的人多吗?

公开数据是累计安装 20,468 次,近一周安装 828 次,下载 6,425 次,GitHub 229 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

spring-boot-security-jwt 安全吗?

第三方扫描有提醒项,说明存在需要人工确认的行为。安装前请打开源码看清它读了什么、联网到哪里。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方扫描存在提醒项或未通过项,需要人工逐条确认。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
spring-boot-security-jwt

spring boot 安全 JWT · 本页

20,468229接触敏感数据未明确有提醒

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Spring Boot JWT Security

JWT authentication and authorization patterns for Spring Boot 3.5.x using Spring Security 6.x and JJWT. Covers token generation, validation, refresh strategies, RBAC/ABAC, and OAuth2 integration.

Overview

This skill provides implementation patterns for stateless JWT authentication in Spring Boot applications. It covers the complete authentication flow including token generation with JJWT 0.12.6, Bearer/cookie-based authentication, refresh token rotation, and method-level authorization with @PreAuthorize expressions.

Key capabilities:

  • Access and refresh token generation with configurable expiration
  • Bearer token and HttpOnly cookie authentication strategies
  • Integration with Spring Data JPA and OAuth2 providers
  • RBAC with role/permission-based @PreAuthorize rules
  • Token revocation and blacklisting for logout/rotation

When to Use

Activate when user requests involve:

  • "Implement JWT authentication", "secure REST API with tokens"
  • "Spring Security 6.x configuration", "SecurityFilterChain setup"
  • "Role-based access control", "RBAC", ` @PreAuthorize `
  • "Refresh token", "token rotation", "token revocation"
  • "OAuth2 integration", "social login", "Google/GitHub auth"
  • "Stateless authentication", "SPA backend security"
  • "JWT filter", "OncePerRequestFilter", "Bearer token"
  • "Cookie-based JWT", "HttpOnly cookie"
  • "Permission-based access control", "custom PermissionEvaluator"

Quick Reference

Dependencies (JJWT 0.12.6)

ArtifactScope
spring-boot-starter-securitycompile
spring-boot-starter-oauth2-resource-servercompile
io.jsonwebtoken:jjwt-api:0.12.6compile
io.jsonwebtoken:jjwt-impl:0.12.6runtime
io.jsonwebtoken:jjwt-jackson:0.12.6runtime
spring-security-testtest

See references/jwt-quick-reference.md for Maven and Gradle snippets.

Key Configuration Properties

PropertyExample ValueNotes
jwt.secret${JWT_SECRET}Min 256 bits, never hardcode
jwt.access-token-expiration90000015 min in milliseconds
jwt.refresh-token-expiration6048000007 days in milliseconds
jwt.issuermy-appValidated on every token
jwt.cookie-namejwt-tokenFor cookie-based auth
jwt.cookie-http-onlytrueAlways true in production
jwt.cookie-securetrueAlways true with HTTPS

Authorization Annotations

AnnotationExample
@PreAuthorize("hasRole('ADMIN')")Role check
@PreAuthorize("hasAuthority('USER_READ')")Permission check
@PreAuthorize("hasPermission(#id, 'Doc', 'READ')")Domain object check
@PreAuthorize("@myService.canAccess(#id)")Spring bean check

Instructions

Step 1 — Add Dependencies

Include spring-boot-starter-security, spring-boot-starter-oauth2-resource-server, and the three JJWT artifacts in your build file. See references/jwt-quick-reference.md for exact Maven/Gradle snippets.

Step 2 — Configure application.yml

jwt:
  secret: ${JWT_SECRET:change-me-min-32-chars-in-production}
  access-token-expiration: 900000
  refresh-token-expiration: 604800000
  issuer: my-app
  cookie-name: jwt-token
  cookie-http-only: true
  cookie-secure: false   # true in production

See references/jwt-complete-configuration.md for the full properties reference.

Step 3 — Implement JwtService

Core operations: generate access token, generate refresh token, extract username, validate token.

@Service
public class JwtService {

    public String generateAccessToken(UserDetails userDetails) {
        return Jwts.builder()
            .subject(userDetails.getUsername())
            .issuer(issuer)
            .issuedAt(new Date())
            .expiration(new Date(System.currentTimeMillis() + accessTokenExpiration))
            .claim("authorities", getAuthorities(userDetails))
            .signWith(getSigningKey())
            .compact();
    }

    public boolean isTokenValid(String token, UserDetails userDetails) {
        try {
            String username = extractUsername(token);
            return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
        } catch (JwtException e) {
            return false;
        }
    }
}

See references/jwt-complete-configuration.md for the complete JwtService including key management and claim extraction.

Step 4 — Create JwtAuthenticationFilter

Extend OncePerRequestFilter to extract a JWT from the Authorization: Bearer header (or HttpOnly cookie), validate it, and set the SecurityContext.

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            chain.doFilter(request, response);
            return;
        }
        String jwt = authHeader.substring(7);
        String username = jwtService.extractUsername(jwt);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            if (jwtService.isTokenValid(jwt, userDetails)) {
                UsernamePasswordAuthenticationToken authToken =
                    new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }
        chain.doFilter(request, response);
    }
}

See references/configuration.md for the cookie-based variant.

Step 5 — Configure SecurityFilterChain

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(AbstractHttpConfigurer::disable)
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**", "/swagger-ui/**").permitAll()
                .anyRequest().authenticated()
            )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

See references/jwt-complete-configuration.md for CORS, logout handler, and OAuth2 login integration.

Step 6 — Create Authentication Endpoints

Expose /register, /authenticate, /refresh, and /logout via @RestController. Return accessToken + refreshToken in the response body (and optionally set an HttpOnly cookie).

See references/examples.md for the complete AuthenticationController and AuthenticationService.

Step 7 — Implement Refresh Token Strategy

Store refresh tokens in the database with user_id, expiry_date, revoked, and expired columns. On /refresh, verify the stored token, revoke it, and issue a new pair (token rotation).

See references/token-management.md for RefreshToken entity, rotation logic, and Redis-based blacklisting.

Step 8 — Add Authorization Rules

Use @EnableMethodSecurity and @PreAuthorize annotations for fine-grained control:

@PreAuthorize("hasRole('ADMIN')")
public Page<UserResponse> getAllUsers(Pageable pageable) { ... }

@PreAuthorize("hasPermission(#documentId, 'Document', 'READ')")
public Document getDocument(Long documentId) { ... }

See references/authorization-patterns.md for RBAC entity model, PermissionEvaluator, and ABAC patterns.

Step 9 — Write Security Tests

@SpringBootTest
@AutoConfigureMockMvc
class AuthControllerTest {

    @Test
    void shouldDenyAccessWithoutToken() throws Exception {
        mockMvc.perform(get("/api/orders"))
            .andExpect(status().isUnauthorized());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void shouldAllowAdminAccess() throws Exception {
        mockMvc.perform(get("/api/admin/users"))
            .andExpect(status().isOk());
    }
}

See references/testing.md and references/jwt-testing-guide.md for full test suites, Testcontainers setup, and a security test checklist.

Best Practices

Token Security

  • Use minimum 256-bit secret keys — load from environment variables, never hardcode
  • Set short access token lifetimes (15 min); use refresh tokens for longer sessions
  • Implement token rotation: revoke old refresh token when issuing a new one
  • Use jti (JWT ID) claim for blacklisting on logout

Cookie vs Bearer Header

  • Prefer HttpOnly cookies for browser clients (XSS-safe)
  • Use Authorization: Bearer header for mobile/API clients
  • Set Secure, SameSite=Lax or Strict on cookies in production

Spring Security 6.x

  • Use SecurityFilterChain bean — never extend WebSecurityConfigurerAdapter
  • Disable CSRF only for stateless APIs; keep it enabled for session-based flows
  • Use @EnableMethodSecurity instead of deprecated @EnableGlobalMethodSecurity
  • Validate iss and aud claims; reject tokens from untrusted issuers

Performance

  • Cache UserDetails with @Cacheable to avoid DB lookup on every request
  • Cache signing key derivation (avoid re-computing HMAC key per request)
  • Use Redis for refresh token storage at scale

What NOT to Do

  • Do not store sensitive data (passwords, PII) in JWT claims — claims are only signed, not encrypted
  • Do not issue tokens with infinite lifetime
  • Do not accept tokens without validating signature and expiration
  • Do not share signing keys across environments

Examples

Basic Authentication Flow

@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @PostMapping("/authenticate")
    public ResponseEntity<AuthResponse> authenticate(
            @RequestBody LoginRequest request) {
        return ResponseEntity.ok(authService.authenticate(request));
    }

    @PostMapping("/refresh")
    public ResponseEntity<AuthResponse> refresh(@RequestBody RefreshRequest request) {
        return ResponseEntity.ok(authService.refreshToken(request.refreshToken()));
    }

    @PostMapping("/logout")
    public ResponseEntity<Void> logout() {
        authService.logout();
        return ResponseEntity.ok().build();
    }
}

JWT Authorization on Controller Method

@RestController
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ADMIN')")
public class AdminController {

    @GetMapping("/users")
    public ResponseEntity<List<UserResponse>> getAllUsers() {
        return ResponseEntity.ok(adminService.getAllUsers());
    }
}

See references/examples.md for complete entity models and service implementations.

References

FileContent
references/jwt-quick-reference.mdDependencies, minimal service, common patterns
references/jwt-complete-configuration.mdFull config: properties, SecurityFilterChain, JwtService, OAuth2 RS
references/configuration.mdJWT config beans, CORS, CSRF, error handling, session options
references/examples.mdComplete application setup: controllers, services, entities
references/authorization-patterns.mdRBAC/ABAC entity model, PermissionEvaluator, SpEL expressions
references/token-management.mdRefresh token entity, rotation, blacklisting with Redis
references/testing.mdUnit and MockMvc tests, test utilities
references/jwt-testing-guide.mdTestcontainers, load testing, security test checklist
references/security-hardening.mdSecurity headers, HSTS, rate limiting, audit logging
references/performance-optimization.mdCaffeine cache config, async validation, connection pooling
references/oauth2-integration.mdGoogle/GitHub OAuth2 login, OAuth2UserService
references/microservices-security.mdInter-service JWT propagation, resource server config
references/migration-spring-security-6x.mdMigration from Spring Security 5.x
references/troubleshooting.mdCommon errors, debugging tips

Constraints and Warnings

Security Constraints

  • JWT tokens are signed but not encrypted — do not include sensitive data in claims
  • Always validate exp, iss, and aud claims before trusting the token
  • Signing keys must be at least 256 bits; never use weak keys in production
  • Load secrets from environment variables or secure vaults, never from config files
  • SameSite cookie attribute is essential for CSRF protection in cookie-based flows

Spring Security 6.x Constraints

  • WebSecurityConfigurerAdapter is removed — use SecurityFilterChain beans only
  • @EnableGlobalMethodSecurity is deprecated — use @EnableMethodSecurity
  • Lambda DSL is required for HttpSecurity configuration (no method chaining)
  • WebSecurityConfigurerAdapter.order() replaced by @Order on @Configuration classes

Token Constraints

  • Access tokens should expire in 5-15 minutes for security
  • Refresh tokens should be stored server-side (DB or Redis), never in localStorage
  • Implement token blacklisting for immediate revocation on logout
  • jti claim is required for token blacklisting to work correctly

Related Skills

  • spring-boot-dependency-injection — Constructor injection patterns used throughout
  • spring-boot-rest-api-standards — REST API security patterns and error handling
  • unit-test-security-authorization — Testing Spring Security configurations
  • spring-data-jpa — User entity and repository patterns
  • spring-boot-actuator — Security monitoring and health endpoints

平台分布

Codex

35.88%
按下载量换算2,305

Claude

31.08%
按下载量换算1,997

Cursor

20.95%
按下载量换算1,346

Gemini CLI

10.07%
按下载量换算647

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在提醒或未通过项,安装前请自行复核。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills