Đến nội dung chính
notes.vinhnq.com

Tìm kiếm

SecuritySenior16 phút đọc

Spring Security cho REST API: filter chain stateless, đăng nhập và JWT với resource server

Ôn 15 thẻ
Trong bài này

Cụm bài Spring Security cho REST API: 1. JWT với resource server · 2. Refresh token và phân quyền

Lý thuyết JWT, session và bẫy của token đã có ở bài xác thực: session cookie và JWT; bài này là phần làm thật trên Spring Boot 4 và Spring Security 7. Đọc xong, bạn tự cấu hình được một API stateless: đăng nhập trả access token, mọi request sau mang Authorization: Bearer, lỗi 401/403 trả JSON đúng chuẩn. Mọi đoạn code lấy từ một lab đã chạy test (JDK 21, Boot 4.0.3).

1. Filter chain cho API stateless

Ý chính: Spring Security là một dãy servlet filter chạy trước DispatcherServlet. Với API, bạn khai báo một chain riêng cho /api/**, không session, không CSRF, xác thực bằng bearer token.

Bản stateful cho web render ở server (DelegatingFilterProxy, FilterChainProxy, form login, session và CSRF) có ở form login với Spring Security; bài này chỉ nêu chỗ khác.

flowchart LR
  R[Request] --> C[CorsFilter]
  C --> B[BearerTokenAuthenticationFilter]
  B --> E[ExceptionTranslationFilter]
  E --> A[AuthorizationFilter]
  A --> D[DispatcherServlet và controller]
  B -.token sai.-> P401[401 qua AuthenticationEntryPoint]
  A -.thiếu quyền.-> P403[403 qua AccessDeniedHandler]
  • BearerTokenAuthenticationFilter: lấy token từ header, gọi JwtDecoder, đặt Authentication vào SecurityContext.
  • ExceptionTranslationFilter: bắt exception của các filter sau nó. Chưa xác thực → 401, đã xác thực mà thiếu quyền → 403.
  • AuthorizationFilter: kiểm quy tắc authorizeHttpRequests bằng AuthorizationManager.

Cấu hình thật của lab (rút phần CORS và bean xuống dưới):

@Bean
SecurityFilterChain api(HttpSecurity http, PermissionAuthorizationManager permissionCheck,
                        ProblemJsonSecurityHandlers problems) throws Exception {
    http.securityMatcher("/api/**")
        .csrf(csrf -> csrf.disable())                 // access token đi trong header, không phải cookie
        .cors(Customizer.withDefaults())
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(auth -> auth
            .requestMatchers(HttpMethod.POST, "/api/v1/auth/login", "/api/v1/auth/refresh").permitAll()
            .requestMatchers(HttpMethod.POST, "/api/v1/auth/logout").authenticated()
            .requestMatchers("/api/v1/**").access(permissionCheck)   // phần 2
            .anyRequest().denyAll())                                  // deny-by-default
        .oauth2ResourceServer(rs -> rs
            .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter()))
            .authenticationEntryPoint(problems)
            .accessDeniedHandler(problems))
        .exceptionHandling(e -> e.authenticationEntryPoint(problems).accessDeniedHandler(problems));
    return http.build();
}

anyRequest().denyAll() ở cuối là quy tắc “cấm mặc định”: endpoint mới quên khai báo quyền sẽ trả 403 thay vì mở toang.

2. Resource server, authorization server hay IdP ngoài

Ý chính: resource server chỉ kiểm token; authorization server phát token theo chuẩn OAuth2. API đơn lẻ tự phát JWT HS256 là đủ; nhiều service hoặc cần SSO, MFA thì dùng IdP (Keycloak, Auth0, Cognito) với RS256 + JWKS.

Lựa chọn Hợp khi Cái giá
Tự phát JWT HS256 + resource server Một API, một frontend của chính mình Tự lo login, refresh, khoá; mọi service kiểm token đều cầm cùng secret
Spring Authorization Server Bạn phải là nhà cung cấp OAuth2 cho bên thứ ba Nhiều code, nhiều luồng, khó vận hành
IdP ngoài (Keycloak…) Nhiều service, SSO, MFA, social login Thêm một hệ thống; API chỉ cần issuer-uri

Với HS256, ai giữ secret là ký được token. Có từ hai service trở lên thì chuyển sang khoá bất đối xứng (RS256/ES256): IdP giữ private key, service chỉ tải public key qua JWKS. Cấu hình JWKS và kiểm aud đã có ở mục 7 bài xác thực.

Đừng tự viết OncePerRequestFilter đọc JWT như nhiều tutorial: dùng starter spring-boot-starter-security-oauth2-resource-server, bạn được sẵn việc tách header, kiểm chữ ký, exp/nbf, và lỗi 401 kèm header WWW-Authenticate đúng RFC 6750.

3. Lưu mật khẩu và nạp user

Ý chính: dùng DelegatingPasswordEncoder (hash có tiền tố {bcrypt}) để sau này đổi thuật toán mà không vỡ hash cũ; UserDetailsService nạp user theo email và báo lỗi giống hệt khi sai mật khẩu.

@Bean
PasswordEncoder passwordEncoder() {
    // {bcrypt}$2a$10$... : tiền tố cho phép chuyển sang argon2 sau này
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String email) {
    var u = users.findByEmailIgnoreCase(email)            // @EntityGraph nạp luôn roles
            .orElseThrow(() -> new UsernameNotFoundException("Bad credentials"));
    return User.withUsername(u.getEmail())
            .password(u.getPassword())
            .roles(u.getRoles().stream().map(r -> r.getName()).toArray(String[]::new)) // -> ROLE_xxx
            .build();
}

DaoAuthenticationProvider mặc định đã ẩn UsernameNotFoundException thành BadCredentialsException, nên kẻ tấn công không dò được email nào tồn tại. Thông điệp trong exception vẫn nên trung tính, phòng khi ai đó log nó ra.

4. Endpoint đăng nhập: AuthenticationManager rồi ký JWT

Ý chính: controller không tự so mật khẩu; nó đưa email + mật khẩu cho AuthenticationManager, nhận về Authentication đã xác thực, rồi gọi JwtService ký access token.

sequenceDiagram
  participant SPA
  participant API as AuthController
  participant AM as AuthenticationManager
  participant DB
  SPA->>API: POST /api/v1/auth/login {email, password}
  API->>AM: authenticate(unauthenticated token)
  AM->>DB: loadUserByUsername(email)
  AM-->>API: Authentication (ROLE_ADMIN, FACTOR_PASSWORD)
  API-->>SPA: 200 {accessToken} + Set-Cookie refresh_token
@PostMapping("/login")
public ResponseEntity<ApiResponse<TokenResponse>> login(@Valid @RequestBody LoginRequest req) {
    Authentication auth = authManager.authenticate(
            UsernamePasswordAuthenticationToken.unauthenticated(req.email(), req.password()));
    var user = users.findByEmailIgnoreCase(auth.getName()).orElseThrow();
    // Spring Security 7 thêm FACTOR_PASSWORD; chỉ đưa ROLE_ vào token.
    var roles = auth.getAuthorities().stream().map(a -> a.getAuthority())
            .filter(a -> a.startsWith("ROLE_")).map(a -> a.substring(5)).toList();
    return withTokens(jwtService.issueAccessToken(user.getEmail(), roles), refreshTokens.issue(user));
}

Bean AuthenticationManager khai báo tường minh, vì Boot không tự expose nó ra cho controller:

@Bean
AuthenticationManager authenticationManager(UserDetailsService uds, PasswordEncoder encoder) {
    DaoAuthenticationProvider provider = new DaoAuthenticationProvider(uds);
    provider.setPasswordEncoder(encoder);
    return new ProviderManager(provider);
}

Sai mật khẩu ném BadCredentialsException; một @ExceptionHandler trong controller đổi nó thành 401 ProblemDetail “Invalid email or password”. Handler này chạy được vì lỗi xảy ra trong controller, không phải trong filter.

5. Ký và kiểm token

Ý chính: encoder và decoder dùng chung một SecretKey ≥ 256 bit lấy từ biến môi trường; decoder phải cố định HS256 và kiểm iss, không tin thuật toán ghi trong header token.

public String issueAccessToken(String email, Collection<String> roles) {
    Instant now = Instant.now();
    JwtClaimsSet claims = JwtClaimsSet.builder()
            .issuer(props.issuer()).subject(email)
            .issuedAt(now).expiresAt(now.plus(props.accessTtl()))   // 15 phút
            .claim("roles", List.copyOf(roles))                      // không mật khẩu, không PII
            .build();
    JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
    return encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
}
Bean SecretKey, JwtEncoder, JwtDecoder và cấu hình
@Bean
SecretKey jwtKey(JwtProperties props) {
    byte[] bytes = Base64.getDecoder().decode(props.secret());
    if (bytes.length < 32) throw new IllegalStateException("HS256 key must be at least 256 bits");
    return new SecretKeySpec(bytes, "HmacSHA256");
}

@Bean
JwtEncoder jwtEncoder(SecretKey jwtKey) {
    return new NimbusJwtEncoder(new ImmutableSecret<>(jwtKey));
}

@Bean
JwtDecoder jwtDecoder(SecretKey jwtKey, JwtProperties props) {
    NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(jwtKey)
            .macAlgorithm(MacAlgorithm.HS256)          // cố định thuật toán
            .build();
    decoder.setJwtValidator(JwtValidators.createDefaultWithIssuer(props.issuer())); // exp, nbf, iss
    return decoder;
}
# Chỉ để dev; môi trường dùng chung đọc từ biến môi trường / secret manager
app.jwt.secret=${JWT_SECRET:ZGV2LW9ubHktc2VjcmV0LWRldi1vbmx5LXNlY3JldC0zMmJ5dGVzISE=}
app.jwt.issuer=https://hr.example.dev
app.jwt.access-ttl=15m
app.jwt.refresh-ttl=7d

JwtProperties là record có @ConfigurationProperties(prefix = "app.jwt"), kiểu Duration cho TTL, và ném lỗi lúc khởi động nếu thiếu secret: app không lên còn hơn lên với secret rỗng.

Ba điều decoder phải làm, và lab đã kiểm bằng test (token bị sửa hai ký tự cuối → 401):

  • Cố định thuật toán: chống tấn công đổi alg (RS256 → HS256 dùng public key làm secret, hoặc alg: none).
  • Kiểm iss (và aud khi có nhiều API): token của hệ khác không dùng được ở đây.
  • Khoá đủ dài: HMAC-SHA256 cần ≥ 256 bit; secret kiểu “123456” brute-force được offline từ một token bất kỳ.

6. Từ claim roles sang ROLE_xxx

Ý chính: resource server mặc định đọc claim scope/scp và tạo authority SCOPE_xxx. Token của mình mang roles, nên phải cấu hình JwtAuthenticationConverter để có ROLE_xxx cho hasRole.

static JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter roles = new JwtGrantedAuthoritiesConverter();
    roles.setAuthoritiesClaimName("roles");   // claim "roles": ["HR"]
    roles.setAuthorityPrefix("ROLE_");        // -> ROLE_HR
    JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
    converter.setJwtGrantedAuthoritiesConverter(roles);
    return converter;
}

Không đặt cả danh sách permission vào token: token phình to, và đổi quyền phải chờ token hết hạn. Lab chỉ để role thô; permission tra ở server (phần 2).

7. 401 và 403 dạng JSON

Ý chính: lỗi xác thực và phân quyền ở tầng URL sinh ra trong filter, trước DispatcherServlet, nên @RestControllerAdvice không bao giờ thấy chúng. Viết AuthenticationEntryPoint (401) và AccessDeniedHandler (403) để trả cùng format ProblemDetail.

@Override
public void commence(HttpServletRequest req, HttpServletResponse res, AuthenticationException ex) throws IOException {
    res.setHeader("WWW-Authenticate", "Bearer");
    write(res, 401, "Unauthorized", "Missing, invalid or expired access token");
}

@Override
public void handle(HttpServletRequest req, HttpServletResponse res, AccessDeniedException ex) throws IOException {
    write(res, 403, "Forbidden", "You do not have permission for " + req.getMethod() + " " + req.getRequestURI());
}

Gắn handler vào cả oauth2ResourceServer(...) lẫn exceptionHandling(...): cái đầu bắt token sai, cái sau bắt request không có token. Test trong lab khẳng định: không token → 401, có WWW-Authenticate: Bearer, content type application/problem+json. Format lỗi chung của API và ProblemDetail: xem xử lý lỗi Spring Boot.

Không đưa chi tiết lý do (hết hạn, sai chữ ký) vào body 401: log ở server là đủ, client chỉ cần biết phải refresh hay đăng nhập lại.

8. CORS cho SPA và chỗ giữ access token

Ý chính: SPA ở origin khác cần CORS cho đúng origin, cho phép header Authorization và allowCredentials(true) (để gửi cookie refresh). Access token giữ trong bộ nhớ JavaScript, không trong localStorage.

CorsConfiguration cfg = new CorsConfiguration();
cfg.setAllowedOrigins(origins);                 // đúng origin, không "*" khi có credentials
cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE"));
cfg.setAllowedHeaders(List.of("Authorization", "Content-Type"));
cfg.setAllowCredentials(true);
cfg.setMaxAge(3600L);

.cors(Customizer.withDefaults()) trong chain làm preflight OPTIONS được trả lời trước khi bị đòi token. Thiếu dòng này, trình duyệt báo lỗi CORS dù Postman vẫn gọi được (giải thích ở bài web và HTTP).

9. Lab: đã chạy gì

Ý chính: lab HR API (Spring Boot 4.0.3, JDK 21, H2) chạy mvn test được 29 test: 28 qua, 1 bỏ qua (test Testcontainers PostgreSQL, máy không có Docker engine chạy được).

  • Chạy app với profile dev: POST /api/v1/auth/login trả 200 kèm Set-Cookie: refresh_token=...; Path=/api/v1/auth; HttpOnly; Secure; SameSite=Strict.
  • GET /api/v1/users/1 không token → 401, WWW-Authenticate: Bearer.
  • Test tích hợp (@SpringBootTest + MockMvc): sai mật khẩu → 401, token bị sửa → 401, token lấy từ login gọi được API.
Senior sẽ làm khác gì ở lab này
  • Nhiều service: chuyển sang RS256/ES256 với JWKS, xoay khoá theo kid; HS256 buộc mọi service giữ secret ký được token.
  • Kiểm aud: thêm JwtClaimValidator cho audience khi có hơn một API dùng chung issuer.
  • Rate limit endpoint login (theo IP và theo email) và khoá tạm sau nhiều lần sai; BCrypt chậm là cố ý nhưng cũng là chỗ bị DoS.
  • Audit log đăng nhập thành công/thất bại, không log mật khẩu hay token.
  • Không tự phát token nếu tổ chức đã có IdP: API chỉ cần spring.security.oauth2.resourceserver.jwt.issuer-uri.
  • Test bảo mật bằng test: các trường hợp alg: none, token hết hạn (inject Clock), issuer khác, đều nên có test tự động.

Ghi nhớ

  • Vẽ được thứ tự filter từ request tới controller, và chỉ ra chỗ sinh 401, chỗ sinh 403.
  • Giải thích được vì sao tắt CSRF an toàn cho chain dùng bearer header, và khi nào không còn an toàn.
  • Biết ba điều JwtDecoder phải kiểm và vì sao HS256 không hợp cho nhiều service.
  • Cấu hình được JwtAuthenticationConverter để hasRole hoạt động với claim roles.
  • Giải thích được vì sao @RestControllerAdvice không bắt được lỗi 401/403 ở tầng filter.

Câu hỏi phỏng vấn

Junior

JWT có được mã hoá không? Có nên để email, số điện thoại trong payload?

Không, JWT thông thường (JWS) chỉ được ký; payload là Base64url ai cũng đọc được. Chỉ để định danh tối thiểu.

Chữ ký chống sửa chứ không chống đọc. Email làm sub thì chấp nhận được trong hệ nội bộ, nhưng không để mật khẩu, số thẻ hay dữ liệu cá nhân nhạy cảm. Cần giấu nội dung thì dùng JWE, hoặc token opaque tra ở server.

401 và 403 khác nhau thế nào trong Spring Security?

401: chưa xác thực được (không có token, token sai, hết hạn). 403: đã biết bạn là ai nhưng không đủ quyền.

ExceptionTranslationFilter quyết định: AuthenticationException đi tới AuthenticationEntryPoint (401), AccessDeniedException của người đã xác thực đi tới AccessDeniedHandler (403).

Mid

Vì sao API dùng JWT trong header có thể tắt CSRF?

Vì CSRF dựa vào việc trình duyệt tự đính kèm cookie; header Authorization thì trình duyệt không tự gửi.

Trang độc không đọc được token trong bộ nhớ của SPA nên không giả được request. Điều kiện là không có credential nào đi bằng cookie trên chain đó. Endpoint refresh dùng cookie thì phòng bằng SameSite=Strict, path hẹp và CORS chặt.

Vì sao @RestControllerAdvice không bắt được lỗi token hết hạn?

Vì lỗi xảy ra trong security filter, trước DispatcherServlet; controller advice chỉ thấy exception ném ra trong quá trình xử lý của MVC.

Muốn format thống nhất thì cài AuthenticationEntryPoint và AccessDeniedHandler viết ProblemDetail. Ngược lại, AccessDeniedException từ @PreAuthorize ném ra trong controller thì advice có thấy, nên handler catch-all có thể biến nó thành 500.

Cấu hình mặc định của resource server biến claim nào thành authority?

Claim scope (hoặc scp), tách theo dấu cách, thêm tiền tố SCOPE_.

Muốn dùng hasRole('ADMIN') với claim roles thì cấu hình JwtGrantedAuthoritiesConverter đọc roles và đặt tiền tố ROLE_, rồi gắn vào JwtAuthenticationConverter. Không nên nhét role vào scope vì scope là quyền uỷ cho client.

Senior

Khi nào tự phát JWT HS256 trong API là đủ, khi nào nên dùng IdP?

Một API với frontend của chính mình thì HS256 tự phát là đủ; nhiều service, SSO, MFA hay bên thứ ba thì dùng IdP với khoá bất đối xứng.

Với HS256, mọi bên kiểm token đều có thể ký token, nên rò secret ở một service là rò cả hệ. IdP giữ private key, service chỉ cần public key qua JWKS, xoay khoá theo kid không cần deploy. Cái giá là thêm một hệ thống phải vận hành và phụ thuộc vào nó lúc đăng nhập.

Một đồng nghiệp đưa nguyên getAuthorities() vào claim của token trên Spring Security 7. Có vấn đề gì?

Token sẽ chứa cả FACTOR_PASSWORD (và có thể các authority khác không phải role), làm quyền dựa trên claim bị sai và token mang thông tin thừa.

Security 7 thêm authority yếu tố cho MFA. Chỉ chọn lọc những gì hợp đồng token cần (ở đây là role, bỏ tiền tố ROLE_), và có test khẳng định nội dung claim.

Liệt kê những gì JwtDecoder phải kiểm trong một hệ production.

Chữ ký với thuật toán cố định, exp/nbf có độ lệch đồng hồ nhỏ, iss, aud, và độ dài khoá.

Không lấy thuật toán từ header token (tấn công alg: none hoặc đổi RS256 sang HS256). Với JWKS, chỉ chấp nhận khoá từ issuer tin cậy. Thêm test tự động cho từng trường hợp hỏng.

Từ vựng tiếng Anh

Term Phát âm Nghĩa Ví dụ câu tiếng Anh dùng trong phỏng vấn
filter chain /ˈfɪl.tɚ tʃeɪn/ dãy filter bảo mật “Every API request goes through the security filter chain before it reaches a controller.”
resource server /ˈriː.sɔːrs ˈsɝː.vɚ/ service chỉ kiểm token “Our API is a resource server: it validates tokens but never issues them.”
stateless /ˈsteɪt.ləs/ không giữ phiên “The chain is stateless, so any instance can serve any request.”
bearer token /ˈber.ɚ ˈtoʊ.kən/ token “ai cầm là dùng được” “A bearer token works for whoever holds it, so keep it short-lived.”
entry point /ˈen.tri pɔɪnt/ nơi trả lời 401 “The authentication entry point returns a problem JSON with a Bearer challenge.”
signing key /ˈsaɪ.nɪŋ kiː/ khoá ký “With HS256 the verifying key is also a signing key.”
algorithm pinning /ˈæl.ɡə.rɪ.ðəm ˈpɪn.ɪŋ/ cố định thuật toán “Pinning the algorithm blocks the alg-none trick.”
authority /əˈθɔːr.ə.ti/ quyền (chuỗi) trong Spring “A role is just an authority with the ROLE_ prefix.”
preflight request /ˈpriː.flaɪt rɪˈkwest/ request OPTIONS của CORS “The preflight must pass before the browser sends the real call.”
deny by default /dɪˈnaɪ baɪ dɪˈfɔːlt/ cấm mặc định “We end the rules with denyAll, so a forgotten endpoint is closed, not open.”

Ghi chép dựa trên tài liệu khoá học của Hỏi Dân IT, viết lại và bổ sung theo cách hiểu của mình.