Integrating OAuth2.0 with JWT in Spring Security – Advanced Tutorial

This article explains how to integrate OAuth2.0 with JWT token issuance in Spring Security, covering transparent vs opaque tokens, server‑side configuration, resource‑server validation, testing with Postman, and key source‑code snippets for a complete end‑to‑end authentication solution.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Integrating OAuth2.0 with JWT in Spring Security – Advanced Tutorial

This article is the third installment of the "Spring Security Advanced" series and demonstrates how to integrate OAuth2.0 with JWT token issuance, which is the mainstream token format used in many enterprises today.

What is JWT? In the OAuth2.0 model tokens are either transparent (e.g., JWT) or opaque (e.g., a UUID stored in a token store). Transparent tokens embed user information, allowing resource services to validate them locally without calling the authorization server. A JWT consists of three parts – header, payload, and signature – illustrated by the following example:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.<br/>eyJhdWQiOlsicmVzMSJdLCJ1c2VyX25hbWUiOiJ1c2VyIiwic2NvcGUiOlsiYWxsIl0sImV4cCI6MTYzODYwNTcxOCwiYXV0aG9yaXRpZXMiOlsiUk9MRV91c2VyIl0sImp0aSI6ImRkNTVkMjEzLThkMDYtNGY4MC1iMGRmLTdkN2E0YWE2MmZlOSIsImNsaWVudF9pZCI6Im15anN6bCJ9.<br/>koup5-wzGfcSVnaaNfILwAgw2VaTLvRgq2JVnIHYe_Q

The header defines the token type and signing algorithm, the payload carries standard claims (issued‑at, expiration, etc.) and optional custom data, and the signature is generated by signing the first two parts with a secret key.

OAuth2.0 Authorization Server Setup

A new module oauth2-auth-server-jwt is created, reusing the code from the previous article and adding JWT‑specific configuration. Token‑related settings are placed in the AccessTokenConfig class, where the JwtAccessTokenConverter (token enhancer) and JwtTokenStore are defined. The signing key (SIGN_KEY) uses symmetric encryption for demonstration, though the article notes that asymmetric keys are recommended for production.

services.setTokenEnhancer(jwtAccessTokenConverter);

The authorization server also configures DefaultTokenServices to set access‑token and refresh‑token lifetimes (default 12 hours and 30 days).

Resource Server Setup

A separate module oauth2-auth-resource-jwt is created. It reuses the same AccessTokenConfig so that the resource server can decode and verify JWTs using the identical signing key. The ResourceServerTokenServices bean is configured with the JWT token enhancer, and the resource ID and token validation are set in ResourceServerSecurityConfigurer.

Testing

Using Postman, a password‑grant request is sent to /oauth/token to obtain a JWT access token. The returned token is then attached to subsequent resource‑service calls, confirming successful authentication.

Source Code Walkthrough

The article details the two core flows: token acquisition and token validation. Token acquisition starts at the /oauth/token endpoint, implemented by TokenEndpoint#postAccessToken(). It loads client details (e.g., ClientDetailsService) and generates an OAuth2AccessToken via the token granter:

ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest);

The token is ultimately enhanced by JwtAccessTokenConverter#enhance(), producing the final JWT.

Token validation occurs in OAuth2AuthenticationProcessingFilter, which delegates to OAuth2AuthenticationManager.authenticate(). Because JWTs are self‑contained, the resource server validates them locally without remote calls.

All example code and configuration files are provided as images in the original article, and the complete source repository is available on GitHub (access via the public WeChat account "码猿技术专栏" by replying with the keyword "9529").

Final Note

The author encourages readers to like, share, and follow the WeChat public account for more advanced Spring Cloud, Spring Boot, and MyBatis tutorials.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaAuthenticationJWTspring-security
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.