Category: spring_boot
JWT (JSON Web Token)
Published on 26 Jun 2026
Explanation
JWT (JSON Web Token) is a
compact and secure way to authenticate
users in REST APIs. After successful
login, the server generates a token
and sends it to the client.
The client includes this token in
subsequent requests.
Code:
Header.Payload.Signature Example: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiJ9. signature
Explanation
Add JWT dependencies to the Spring
Boot project. These libraries are used
to create, parse, and validate JWT
tokens.
Code:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.5</version>
<scope>runtime</scope>
</dependency>
Explanation
A JWT utility class is responsible
for generating tokens after successful
authentication.
The token contains user information and
an expiration time.
private final String SECRET =
"my-secret-key";
Code:
public String generateToken(
String username) {
return Jwts.builder()
.subject(username)
.issuedAt(new Date())
.expiration(
new Date(
System.currentTimeMillis() + 86400000))
.signWith(
Keys.hmacShaKeyFor(SECRET.getBytes()))
.compact();
}
}
Explanation
Create a login endpoint that validates
user credentials and returns a JWT
token. The client stores this token
and uses it for future API
requests.
Code:
@PostMapping("/login")
public String login(@RequestBody
LoginRequest request) {
if ("admin".equals(
request.getUsername()) &&
"admin123".equals(request.
getPassword())) {
return jwtUtil.generateToken(
request.getUsername());
}
throw new RuntimeException(
"Invalid Credentials");
}
Explanation
Protected endpoints require the JWT token
in the Authorization header. Spring Security
validates the token before allowing access
to secured resources.
Code:
GET /students
Authorization: Bearer
eyJhbGciOiJIUzI1NiJ9...
@RestController
@RequestMapping("/students")
public class StudentController {
@GetMapping
public String getStudents() {
return "Secured Student Data";
}
}