Implementing a JWT-Based Authentication Center with Spring Boot and Java
This article provides a comprehensive guide to building a JWT authentication service in Java, covering JWT fundamentals, Spring Boot configuration, entity and DAO definitions, service interfaces, token generation and parsing, RSA key handling, controller endpoints, testing procedures, and a comparison with traditional session-based authentication.
This article explains how to create a JWT authentication center using Java and Spring Boot, starting with an overview of JSON Web Tokens (JWT) and their three components: Header, Payload, and Signature.
It shows the HMACSHA256 signature formula and demonstrates how to generate RSA key pairs for signing tokens.
Configuration files for a Spring Boot microservice are provided, including dependencies for Nacos discovery, JPA, MySQL, Kafka, Zipkin, and other utilities.
The EcommerceUser entity is defined with JPA annotations, and a corresponding DAO interface extends JpaRepository with custom query methods.
public interface EcommerceUserDao extends JpaRepository
{
EcommerceUser findByUsername(String name);
EcommerceUser findByUsernameAndPassword(String name, String password);
}A service interface IJWTService declares methods for generating tokens, generating tokens with custom expiration, and registering users while returning a token.
public interface IJWTService {
String generateToken(String username, String password) throws Exception;
String generateToken(String username, String password, Integer expireTime) throws Exception;
String registerUserAndGenerateToken(UsernameAndPassword usernameAndPassword) throws Exception;
}The implementation IJWTServiceIpml validates users, creates a LoginUserinfo payload, sets expiration, and signs the token with a private RSA key.
return Jwts.builder()
.claim(CommonCanstant.JWT_USER_INFO_KEY, JSON.toJSONString(loginUserinfo))
.setId(UUID.randomUUID().toString())
.setExpiration(expireDate)
.signWith(getPrivateKey(), SignatureAlgorithm.RS256)
.compact();Utility class TokenParseUtil parses a JWT using the stored public key and extracts the LoginUserinfo object.
public static LoginUserinfo parseUserInfoFromToken(String token) throws Exception {
if (token == null) return null;
Jws
claimsJws = parseToken(token, getPublicKey());
Claims body = claimsJws.getBody();
if (body.getExpiration().before(Calendar.getInstance().getTime())) return null;
return JSON.parseObject(body.get(CommonCanstant.JWT_USER_INFO_KEY).toString(), LoginUserinfo.class);
}The REST controller AuthorityConroller exposes two endpoints: /token for login and token retrieval, and /register for user registration and immediate token issuance, both returning a plain JwtToken object without additional response wrapping.
@PostMapping("/token")
public JwtToken token(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception {
return new JwtToken(ljwtService.generateToken(usernameAndPassword.getUsername(), usernameAndPassword.getPassword()));
}
@PostMapping("/register")
public JwtToken register(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception {
return new JwtToken(ljwtService.registerUserAndGenerateToken(usernameAndPassword));
}JUnit test classes verify token generation, parsing, user creation, and edge cases such as missing users or duplicate registrations.
Finally, the article compares JWT-based stateless authentication with traditional session-based approaches, highlighting differences in scalability, server memory usage, cross‑domain support, expiration handling, and overall system design.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.