Category: java
Introduction to JWT Authentication
Published on 24 Jul 2026
Explanation
JWT (JSON Web Token) is a secure, stateless authentication mechanism used in REST APIs. After successful login, the server generates a signed token, and the client includes it in subsequent requests for authentication instead of using sessions.
Code:
Client Login
β
Spring Boot
β
Generate JWT
β
Client Stores Token
β
Authorization: Bearer <JWT>
Explanation
To implement JWT authentication, include a JWT library in your Spring Boot project. The library is responsible for creating, signing, parsing, and validating JSON Web Tokens using a secret key.
Code:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.6</version>
</dependency>
Explanation
After verifying user credentials, the application generates a JWT containing user information such as username and roles. The token is digitally signed to prevent tampering and has an expiration time for improved security.
Code:
String token = Jwts.builder()
.subject("john")
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() + 3600000))
.signWith(secretKey)
.compact();
Explanation
Every protected request includes the JWT in the Authorization header. Spring Security validates the token's signature, expiration time, and user details before allowing access to secured REST endpoints.
Code:
String username = Jwts.parser()
.verifyWith(secretKey)
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
Explanation
Configure Spring Security so that public endpoints remain accessible while protected APIs require a valid JWT token. A custom JWT authentication filter intercepts requests, validates the token, and authenticates the user before reaching the controller.
Code:
http
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> auth
.requestMatchers("/login").permitAll()
.anyRequest().authenticated());