Implementing Single Sign-On with Spring Security and JWT – A Comprehensive Guide

This article provides a detailed, step‑by‑step tutorial on building a Spring Security‑based Single Sign‑On solution using JWT, covering SSO concepts, JWT structure, RSA encryption, custom authentication filters, Maven project setup, configuration files, and full code examples for both authentication and resource services.

IT Architects Alliance
IT Architects Alliance
IT Architects Alliance
Implementing Single Sign-On with Spring Security and JWT – A Comprehensive Guide

This article explains how to implement Single Sign‑On (SSO) using Spring Security and JWT, offering a complete 20,000‑character guide with code skeletons for quick reference.

1. What is Single Sign‑On

SSO allows a user to log in once and access multiple trusted applications without re‑authenticating.

2. Simple Operation Mechanism

The article uses an analogy of a park with a universal ticket to illustrate the SSO flow, showing user authentication and token validation steps.

3. JWT Introduction

Concept

JWT (JSON Web Token) is a widely used distributed identity verification solution that can generate and verify tokens.

Token Structure

Header – defines token type and signing algorithm.

Payload – stores claims such as username, roles, and expiration (never store passwords).

Signature – base64‑encoded header and payload signed with a secret or private key.

Security Analysis

The signature’s security relies on the secret or private key; using asymmetric RSA encryption prevents the secret from being exposed.

RSA Asymmetric Encryption

RSA generates a public/private key pair; the private key encrypts the token, and the public key verifies it. Advantages: high security; disadvantages: computationally intensive.

4. Authentication Design Analysis

Spring Security uses filters for authentication. The default UsernamePasswordAuthenticationFilter handles username/password verification, while BasicAuthenticationFilter validates tokens.

Modifications for Distributed Authentication

Allow attemptAuthentication to read JSON request bodies.

Replace session storage with JWT generation in successfulAuthentication.

In token verification, extract the token from the Authorization header, parse it with the public key, and set the authentication in the security context.

5. Implementation Steps

5.1 Create Parent Maven Project

Use spring-boot-starter-parent version 2.1.3.RELEASE as the parent.

5.2 Create Common Module

Add JWT dependencies ( jjwt-api, jjwt-impl, jjwt-jackson) and utility classes ( JsonUtils, JwtUtils, RsaUtils).

5.3 Write Test Class to Generate RSA Keys

public class JwtTest { private String privateKey = "c:/tools/auth_key/id_key_rsa"; private String publicKey = "c:/tools/auth_key/id_key_rsa.pub"; @Test public void test1() throws Exception { RsaUtils.generateKey(publicKey, privateKey, "dpb", 1024); } }

5.4 Build Authentication Service

Create Spring Boot application class.

Add RsaKeyProperties to load public/private keys.

Define domain classes UserPojo and RolePojo implementing Spring Security interfaces.

Create MyBatis mapper and XML for user queries.

Implement UserService extending UserDetailsService.

Write custom filters TokenLoginFilter (login) and TokenVerifyFilter (token validation).

Configure Spring Security to disable CSRF, add the custom filters, and enforce stateless sessions.

5.5 Test Authentication Service

Run the service, use Postman to POST credentials, receive a JWT in the Authorization header, and access protected endpoints with the token.

6. Build Resource Service

Set up a second Spring Boot project that only contains the public key (no private key) and reuses the domain and utility classes from the authentication service.

Configure RsaKeyProperties to load only the public key, and use TokenVerifyFilter for token validation. No token‑issuing filter is added.

Implement simple REST controllers (e.g., /user/query, /user/update) and protect them with Spring Security.

7. End‑to‑End Verification

Obtain a JWT from the authentication service, then call the resource service endpoints with the token to confirm successful SSO across services.

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.

JavaAuthenticationJWTSSOspring-security
IT Architects Alliance
Written by

IT Architects Alliance

Discussion and exchange on system, internet, large‑scale distributed, high‑availability, and high‑performance architectures, as well as big data, machine learning, AI, and architecture adjustments with internet technologies. Includes real‑world large‑scale architecture case studies. Open to architects who have ideas and enjoy sharing.

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.