Hackforge Academy

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";
    }
}

๐Ÿš€ Learn Spring Boot with real-world projects

๐Ÿ’ก Build REST APIs step by step

๐Ÿง  Improve backend development skills

๐ŸŽฏ Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

๐Ÿ

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
โš›๏ธ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
โ˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community