spring-boot-security-jwt
Provides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x
Install / Use
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-security-jwtInstalls into whichever agent you are using.
SKILL.md
Installable skill definition
Quality Score
Category
SecuritySupported Platforms
Our assessment of spring-boot-security-jwt
spring-boot-security-jwt scores 83/100 on our quality scale, 859th of 1,115 Security skills we index.
Its SKILL.md is 15 KB long, well organised into 32 sections with 8 code examples: a thorough specification that gives an agent plenty to work with.
It has 353 GitHub stars, a meaningful sign that others use it.
Maintenance, license and trust
- The repository was last updated 26 days ago, so spring-boot-security-jwt is actively maintained.
- It is released under the MIT license, a permissive license that allows use, modification and commercial use with attribution.
- Its trust signals score 100/100, with no cautions. These come from repository metadata, not a code audit — read the skill file before letting an agent act on it.
spring-boot-security-jwt compared with similar skills
All 4 of these similar skills score higher than spring-boot-security-jwt; compare them before choosing.
| Skill | Score | Stars | Updated | Format |
|---|---|---|---|---|
| spring-boot-security-jwt (this skill)by giuseppe-trisciuoglio | 83 | 353 | 26d ago | SKILL.md |
| algorithmic-artby anthropics | 100 | 177.9k | 14d ago | SKILL.md |
| pptxby anthropics | 100 | 177.9k | 14d ago | SKILL.md |
| designby nextlevelbuilder | 100 | 130.2k | 15d ago | SKILL.md |
| ui-ux-pro-maxby nextlevelbuilder | 100 | 130.2k | 15d ago | SKILL.md |
Frequently asked questions
- How do I install spring-boot-security-jwt?
- Run
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-security-jwt. The install tabs above show the steps for each supported agent. - Which AI agents does spring-boot-security-jwt work with?
- It is written for Universal, as a SKILL.md file. Other agents that read the same format can often use it too.
- Is spring-boot-security-jwt safe to use?
- It is MIT-licensed and scores 100/100 on trust signals. Skills are instructions an agent will follow, so read the file before installing it and do not approve commands you do not understand.
- Is spring-boot-security-jwt still maintained?
- The repository was last updated 26 days ago, so spring-boot-security-jwt is actively maintained.
Skill content
View source on GitHubname: spring-boot-security-jwt description: Provides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
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
@PreAuthorizerules - 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)
| Artifact | Scope |
|----------|-------|
| spring-boot-starter-security | compile |
| spring-boot-starter-oauth2-resource-server | compile |
| io.jsonwebtoken:jjwt-api:0.12.6 | compile |
| io.jsonwebtoken:jjwt-impl:0.12.6 | runtime |
| io.jsonwebtoken:jjwt-jackson:0.12.6 | runtime |
| spring-security-test | test |
See references/jwt-quick-reference.md for Maven and Gradle snippets.
Key Configuration Properties
| Property | Example Value | Notes |
|----------|--------------|-------|
| jwt.secret | ${JWT_SECRET} | Min 256 bits, never hardcode |
| jwt.access-token-expiration | 900000 | 15 min in milliseconds |
| jwt.refresh-token-expiration | 604800000 | 7 days in milliseconds |
| jwt.issuer | my-app | Validated on every token |
| jwt.cookie-name | jwt-token | For cookie-based auth |
| jwt.cookie-http-only | true | Always true in production |
| jwt.cookie-secure | true | Always true with HTTPS |
Authorization Annotations
| Annotation | Example |
|-----------|---------|
| @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:chan…[redacted]}
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: Bearerheader for mobile/API clients - Set
Secure,SameSite=LaxorStricton cookies in production
Spring Security 6.x
- Use
SecurityFilterChainbean — never extendWebSecurityConfigurerAdapter - Disable CSRF only for stateless APIs; keep it enabled for session-based flows
- Use
@EnableMethodSecurityinstead of deprecated@EnableGlobalMethodSecurity - Validate
issandaudclaims; reject tokens from untrusted issuers
Performance
- Cache
UserDetailswith@Cacheableto 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 [r
Truncated for display — read the full file on GitHub.
Related Skills
algorithmic-art
177.9kCreating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code, generative art, algorithmic art, flow fields, or particle systems.
pptx
177.9kUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an em…
design
130.2kComprehensive design skill: brand identity, design tokens, UI styling, logo generation (55 styles, Gemini, Atlas Cloud, or MuAPI AI), corporate identity program (50 deliverables, CIP mockups), HTML presentations (Chart.js), banner design (22 styles, social/ads/web/print), icon design (15 styles, SVG…
ui-ux-pro-max
130.2kUI/UX design intelligence for web, mobile, and desktop. This skill should be used when designing, building, reviewing, or fixing interfaces, including pages, components, design systems, accessibility, interaction, responsive layout, typography, color, charts, and stack-specific UI implementation.
Languages
Trust signals
From repository metadata: license, adoption, age and documentation. Not a code audit — see the Safety scan above for what the skill file itself contains.
