惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
阮一峰的网络日志
阮一峰的网络日志
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
V
Visual Studio Blog
Martin Fowler
Martin Fowler
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 叶小钗
I
InfoQ
B
Blog RSS Feed
aimingoo的专栏
aimingoo的专栏
Y
Y Combinator Blog
Blog — PlanetScale
Blog — PlanetScale
IT之家
IT之家
P
Proofpoint News Feed
WordPress大学
WordPress大学
小众软件
小众软件
B
Blog
MongoDB | Blog
MongoDB | Blog
人人都是产品经理
人人都是产品经理
量子位
Hugging Face - Blog
Hugging Face - Blog
月光博客
月光博客

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How Spring does JWT verification based on RS256
Tapas Pal · 2026-05-21 · via DEV Community

Tapas Pal

RS256 JWT flow between two microservices, then how Spring actually validates it internally.

how Spring Security internally validates that JWT step by step.

Here's what the actual code looks like in the Inventory Service (spring-boot-starter-oauth2-resource-server):
application.yml — tell Spring where to fetch the public key:


spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jwk-set-uri: http://auth-service/oauth2/jwks

Enter fullscreen mode Exit fullscreen mode

SecurityConfig.java — configure the filter chain:


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
          .authorizeHttpRequests(auth -> auth
           .requestMatchers("/api/inventory/reserve").hasRole("ORDER_SVC")
              .anyRequest().authenticated()
          )
          .oauth2ResourceServer(oauth2 -> oauth2
              .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthConverter()))
          );
        return http.build();
    }

    @Bean
    public JwtAuthenticationConverter jwtAuthConverter() {
        JwtGrantedAuthoritiesConverter converter = new JwtGrantedAuthoritiesConverter();
        converter.setAuthoritiesClaimName("roles");      // map "roles" claim → GrantedAuthority
        converter.setAuthorityPrefix("ROLE_");
        JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
        jwtConverter.setJwtGrantedAuthoritiesConverter(converter);
        return jwtConverter;
    }
}

Enter fullscreen mode Exit fullscreen mode

InventoryController.java — the endpoint is now protected:


@RestController
@RequestMapping("/api/inventory")
public class InventoryController {

    @PostMapping("/reserve")
    @PreAuthorize("hasRole('ORDER_SVC')")
    public ResponseEntity<String> reserveStock(
            @RequestBody ReserveRequest req,
            @AuthenticationPrincipal Jwt jwt) {   // inject the parsed JWT

        String callerService = jwt.getSubject();  // "order-service"
        // proceed with reservation...
        return ResponseEntity.ok("Reserved for " + callerService);
    }
}

Enter fullscreen mode Exit fullscreen mode

What does BearerTokenAuthenticationFilter do exactly in Spring Security?

What BearerTokenAuthenticationFilter does
It is a OncePerRequestFilter — guaranteed to run exactly once per request, sitting early in Spring Security's filter chain. Its entire job is to bridge the raw HTTP world (a string in a header) to Spring Security's authentication world (a typed Authentication object in the SecurityContext).

Step 1 — Token extraction via DefaultBearerTokenResolver
It reads the Authorization header and strips Bearer from the front. It also optionally checks request parameters (access_token=...) if you configure allowFormEncodedBodyParameter or allowUriQueryParameter. If no token is found at all, it just calls chain.doFilter() — the request passes through unauthenticated, and a later filter or your controller will enforce access.

Step 2 — Wraps the raw token in BearerTokenAuthenticationToken
This is a lightweight container that holds the raw JWT string and is marked as not yet authenticated (isAuthenticated() = false). Think of it as the question — "here's a token, can you validate it?"

Step 3 — Hands off to AuthenticationManager
The filter calls authenticationManager.authenticate(token). The manager routes this to JwtAuthenticationProvider, which calls NimbusJwtDecoder to do the actual RS256 verification, expiry check, issuer check, etc.

Step 4a — On success: populates SecurityContextHolder
If authentication succeeds, the provider returns a fully populated JwtAuthenticationToken (which is authenticated, carries the parsed claims, and has GrantedAuthority objects derived from your roles). The filter stores this in SecurityContextHolder.getContext().setAuthentication(...), then calls chain.doFilter() — the request proceeds to your controller, where @PreAuthorize and @AuthenticationPrincipal work because the context is populated.

Step 4b — On failure: delegates to AuthenticationEntryPoint
If the provider throws JwtValidationException (bad signature, expired, wrong issuer), the filter catches it, clears the SecurityContext (important — prevents stale auth from leaking), and calls authenticationEntryPoint.commence(...), which writes a 401 Unauthorized response with a WWW-Authenticate: Bearer error="invalid_token" header.

Key things it does NOT do
It does not do authorization — that's AuthorizationFilter further down the chain.
It doesn't decode the JWT itself — that's NimbusJwtDecoder.
It doesn't map claims to roles — that's JwtAuthenticationConverter.

The filter's job is purely: extract → wrap → delegate → store or reject.