Step‑by‑Step Guide to Building SSO with JWT and Spring Security

This tutorial explains the concept of Single Sign‑On, demonstrates a simple ticket‑based analogy, introduces JWT structure and RSA signing, and walks through a complete Spring Boot implementation—including project layout, Maven dependencies, configuration files, utility classes, custom authentication and verification filters, security configuration, and Postman testing—so readers can build a secure SSO service from scratch.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Step‑by‑Step Guide to Building SSO with JWT and Spring Security

Single Sign‑On (SSO) allows a user to log in once and gain access to multiple trusted applications without re‑entering credentials. The article starts with a park‑ticket analogy to illustrate the basic workflow, then introduces JSON Web Token (JWT) as the token format and explains its three parts: header, payload, and signature.

JWT and RSA Security

The guide recommends using RSA asymmetric encryption for the signature to keep the private key secret on the authentication server while exposing only the public key to resource services. It shows how to generate RSA key pairs, store them as Base64‑encoded files, and load them at application startup.

Project Structure

A Maven multi‑module project is created:

Parent pom imports spring-boot-starter-parent (version 2.1.3.RELEASE). common module contains shared dependencies such as jjwt-api, jjwt-impl, jjwt-jackson, Lombok, and logging libraries. auth module implements the authentication service. resource module implements a protected resource service.

Configuration Files

Application YAML files define the datasource, MyBatis settings, and RSA key locations. A RsaKeyProperties class annotated with @ConfigurationProperties("rsa.key") loads the public and private keys using RsaUtils during a @PostConstruct method.

Utility Classes

JsonUtils

provides static methods for object‑JSON conversion using Jackson. JwtUtils contains methods to generate tokens (with minute or second expiration) and to parse tokens, extracting the payload into a generic Payload<T> object. RsaUtils handles key generation, reading, and writing of RSA keys.

Domain Objects

UserPojo

implements UserDetails and holds username, password, status, and role information. RolePojo implements GrantedAuthority. Both are annotated with Lombok @Data for boilerplate reduction.

Data Access Layer

MyBatis mapper interfaces and XML files provide a queryByUserName method to retrieve a UserPojo from the t_user table.

Service Layer

UserService

extends UserDetailsService and delegates to the mapper. The implementation is annotated with @Service and @Transactional.

Custom Spring Security Filters

TokenLoginFilter

extends UsernamePasswordAuthenticationFilter. It reads JSON login data, authenticates via AuthenticationManager, and on success generates a JWT signed with the private RSA key, adding it to the Authorization header. On failure it returns a JSON error response. TokenVerifyFilter extends BasicAuthenticationFilter. It extracts the JWT from the Authorization header, validates it with the public RSA key, builds a UsernamePasswordAuthenticationToken with the user’s authorities, and stores it in the security context. If the token is missing or malformed, it returns a 403 JSON response.

Security Configuration

The WebSecurityConfig class disables CSRF, requires authentication for all endpoints, registers the custom filters, and sets the session policy to STATELESS. Passwords are encoded with BCryptPasswordEncoder. The authentication manager is wired to UserService.

Resource Service

The resource service only loads the public RSA key (no private key) and registers TokenVerifyFilter. It defines a simple UserController with /user/query and /user/update endpoints, protected by the SSO token.

Testing

After starting both services, a POST request to /login (via Postman) returns a JWT in the Authorization header. Subsequent requests to protected endpoints include Bearer <token> and receive successful responses if the token is valid.

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.

Spring BootAuthenticationRSAJWTAuthorizationSSOspring-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.