0
0
Spring Bootframework~5 mins

Why JWT matters for APIs in Spring Boot

Choose your learning style9 modes available
Introduction

JWT helps keep API communication safe and lets servers know who is talking without asking for passwords every time.

When you want users to log in once and access many parts of your app without logging in again.
When your API needs to check if a request is from a trusted user quickly.
When you want to share user info securely between different parts of your system.
When you want to avoid storing session info on the server to keep things simple.
When building mobile or single-page apps that talk to your backend API.
Syntax
Spring Boot
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VySWQiLCJleHAiOjE2MzAwMDAwMDB9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

A JWT has three parts separated by dots: header, payload, and signature.

The payload holds user info and expiration time.

Examples
This is how you send a JWT in an API request header.
Spring Boot
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
This is how you create a JWT token using JJWT (common in Spring Boot).
Spring Boot
String token = Jwts.builder()
  .setSubject("userId")
  .setExpiration(new Date(System.currentTimeMillis() + 86400000))
  .signWith(SignatureAlgorithm.HS256, secretKey.getBytes())
  .compact();
Sample Program

This simple Java example using JJWT (common in Spring Boot) creates a JWT token for user "user123" that expires in 1 hour and prints it.

Spring Boot
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

public class JwtExample {
    private static final String secretKey = "mySecretKey";

    public static String createToken(String userId) {
        return Jwts.builder()
            .setSubject(userId)
            .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 1 hour
            .signWith(SignatureAlgorithm.HS256, secretKey.getBytes())
            .compact();
    }

    public static void main(String[] args) {
        String token = createToken("user123");
        System.out.println("Generated JWT Token:");
        System.out.println(token);
    }
}
OutputSuccess
Important Notes

Keep your secret key safe; if someone else gets it, they can create fake tokens.

Tokens expire to keep your app secure and force users to re-authenticate.

JWTs let your API trust requests without storing session info on the server.

Summary

JWTs help APIs know who is making requests safely and quickly.

They let users log in once and keep using the app without repeated logins.

JWTs keep your API stateless and secure by carrying user info inside the token.