Przejdź do treści
Biblioteka skilli
Programowanie · Budowanie i kod

spring-security-jwt

/spring-security-jwt

Pomaga wdrożyć własne tokeny JWT w aplikacji Spring Security, z filtrami uwierzytelniania, kodowaniem haseł i rolami.

Licencja
MIT
Ostatnia zmiana repozytorium
22.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
7
Skrypty
5
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 22.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co sprawdzić przed instalacją
  • 5 skryptów w paczce. Przejrzyj je przed instalacją, bo Claude może je uruchomić.

Skrypty: examples/bad-security-config.java, examples/good-security-config.java, templates/JwtAuthenticationFilter.java, templates/JwtService.java, templates/SecurityConfig.java

Co robi i kiedy

Pomaga wdrożyć własne tokeny JWT w aplikacji Spring Security, z filtrami uwierzytelniania, kodowaniem haseł i rolami.

Oryginalny opis (EN)

Use when an application issues and validates its own first-party JWT access and refresh tokens, including authentication filters, password encoding, RBAC, and method security. For JWTs issued by Keycloak, Auth0, Okta, Cognito, or another authorization server, use oauth2-resource-server.

Jak działa

  1. Dependencies
  2. Security configuration
  3. JWT implementation
  4. JSON 401/403
  5. Auth Controller
  6. Method-Level Security
  7. application.yml
  8. Gotchas
Sekcje z nagłówków SKILL.md, w oryginale · 141 linii, 711 słów
Podgląd SKILL.md
---
name: spring-security-jwt
description: >
  Use when an application issues and validates its own first-party JWT access and refresh tokens,
  including authentication filters, password encoding, RBAC, and method security. For JWTs issued
  by Keycloak, Auth0, Okta, Cognito, or another authorization server, use oauth2-resource-server.
---

# Spring Security — JWT

## Dependencies

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.12.6</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.12.6</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId>
    <version>0.12.6</version>
    <scope>runtime</scope>
</dependency>
```

## Security configuration

Use the compiled [SecurityConfig](templates/SecurityConfig.java) with the filter and service below.
It uses the lambda DSL, stateless bearer authentication, role rules, JSON 401/403 handlers and
disabled servlet registration for the security-chain filter. Bean method injection avoids
constructor cycles between the configuration and its own AuthenticationProvider bean.
Adapt the routes and roles to the project. CSRF disabling applies to header-only bearer APIs;
keep CSRF protection when browsers send authentication cookies automatically.

## JWT implementation

Use the tested [JwtService](templates/JwtService.java) and
[JwtAuthenticationFilter](templates/JwtAuthenticationFilter.java) templates together.
The configuration keys are `app.jwt.secret`, `app.jwt.access-token-expiration`, and
`app.jwt.refresh-token-expiration` (durations in milliseconds).

The filter rejects expired, malformed, tampered, missing-expiration and refresh tokens with
401 and a Bearer challenge. It checks the current user's enabled, locked, account-expired and
credentials-expired flags before authentication. Deleted users also receive 401.
Database outages and downstream application failures must remain server failures, not be
masked as invalid credentials. Invalid supplied tokens are rejected even on public endpoints.

The filter's example error body uses Problem Details. For an existing legacy API, adapt this
response and the entry point below to the established error contract. Never log bearer tokens.
Register a filter bean only in the security chain: disable servlet-container registration
with a `FilterRegistrationBean<JwtAuthenticationFilter>` whose `enabled` flag is false.

These templates illustrate a single-service first-party token contract. Before sharing signing
keys or accepting tokens across services, define and validate issuer and audience, key rotation,
and revocation. Spring Security's resource-server support can also validate custom JWTs; preserve
it when it already fits the application. Token generation is not a complete refresh flow:
retain the rotation/reuse-detection requirements below.

## JSON 401/403

The configuration and filter templates use Problem Details for authentication and authorization
errors. Adapt both together for a legacy error contract. Missing credentials on a protected route
return 401; an authenticated caller without the required role returns 403. An invalid supplied
token returns 401 even when the route permits anonymous access.
Controller advice cannot handle exceptions thrown before the dispatcher servlet.

## Auth Controller

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

    private final AuthService authService;

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

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

    @PostMapping("/register")
    public ResponseEntity<ApiResponse<AuthResponse>> register(@Valid @RequestBody RegisterRequest request) {
        return ResponseEntity.status(201).body(ApiResponse.ok(authService.register(request)));
    }
}

public record AuthResponse(String accessToken, String refreshToken, long expiresIn) {}
```

## Method-Level Security

```java
// On service methods
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(UUID userId) { ... }

@PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
public UserProfile getProfile(UUID userId) { ... }

@PostAuthorize("returnObject.email == authentication.name")
public User findById(UUID id) { ... }
```

## application.yml

```yaml
app:
  jwt:
    secret: ${JWT_SECRET} # min 256-bit base64 encoded key
    access-token-expiration: 900000   # 15 minutes
    refresh-token-expiration: 604800000 # 7 days
```

The example creates refresh tokens but does not implement a refresh endpoint. A production refresh
flow must accept only `type=refresh`, rotate the refresh token on every use, and revoke the previous
token (for example, with a hashed token-family record in a database or Redis).

## Gotchas
- Agent catches AuthenticationException broadly around user lookup - preserve AuthenticationServiceException as a server failure.
- Agent logs in disabled or locked users from valid JWTs - validate current account status as well as claims.
- Agent uses `HttpSecurity.csrf().disable()` old API — use `AbstractHttpConfigurer::disable`
- Agent lets `ExpiredJwtException` escape the filter — expired token becomes a 500 instead of 401; catch in filter
- Agent skips `exceptionHandling()` — clients get empty 401/403 bodies (or a login-page redirect); `@RestControllerAdvice` can't catch filter-level exceptions
- Agent stores JWT secret in code — always `${JWT_SECRET}` from environment (HS256 needs a ≥256-bit key or `Keys.hmacShaKeyFor` throws `WeakKeyException`)
- Agent uses `SessionCreationPolicy.IF_REQUIRED` — must be `STATELESS` for JWT
- Agent validates only signature and expiry — the bearer filter must accept `type=access` tokens only; refresh tokens belong to a separate refresh endpoint
- Agent forgets `@EnableMethodSecurity` for `@PreAuthorize` to work
- Agent uses BCrypt strength < 10 — use 12 for production
- Agent puts token validation logic in controller — belongs in filter
- Agent puts refresh tokens in localStorage examples — recommend httpOnly cookies or secure storage; refresh tokens are long-lived credentials
Pliki w paczce (7)
  • SKILL.md 7 KB
  • agents/openai.yaml 1 KB
  • examples/bad-security-config.java 1 KB
  • examples/good-security-config.java 4 KB
  • templates/JwtAuthenticationFilter.java 4 KB
  • templates/JwtService.java 3 KB
  • templates/SecurityConfig.java 4 KB

Wersje

RepozytoriumWynikLicencja
Ta strona · rrezartprebreza/spring-boot-skills100MIT
rrezartprebreza/spring-boot-skills100MIT

Migawka bazy z 13.11.2026 · wersja paczki d59cdd2c8970 (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 3 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100oauth2-resource-server
    Konfiguruje Spring Boot jako serwer zasobów OAuth2: waliduje tokeny JWT od zewnętrznego dostawcy (Keycloak, Auth0, Okta, Cognito), wyciąga claims i wdraża autoryzację opartą na zakresach.
  • 100oauth2-resource-server
    Ustawia aplikację Spring Boot jako serwer zasobów OAuth2, który sprawdza JWT z Keycloak, Auth0, Okta lub Cognito, odczytuje claims i egzekwuje uprawnienia na podstawie zakresów.
  • 100spring-authorization-server
    Wspiera budowę dostawców OAuth 2.1 i OpenID Connect w Spring Authorization Server: endpoint tokenów, wydawanie tokenów JWT i własny dostawca OAuth.
  • 100spring-boot-security-jwt
    Wspiera uwierzytelnianie i autoryzację JWT w Spring Boot 3.5.x: generowanie tokenów w JJWT, Bearer i cookie, integrację z bazą i OAuth2 oraz RBAC w Spring Security 6.x.
  • 100spring-security
    Konfiguruje, testuje i przegląda Spring Security 6 i 7: łańcuch filtrów, OAuth2 z JWT, logowanie OIDC, CSRF i CORS.
  • 100spring-security
    Dodaje do Spring Boot 4 zabezpieczenia JWT: konfigurację, mapowanie ról i uprawnień oraz testy.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.