Mastering JWT: Secure API Authentication with Spring Boot

This guide explains the fundamentals of JSON Web Tokens, their structure and claim types, typical use cases such as authorization and secure data exchange, and provides a step‑by‑step Spring Boot implementation including dependency setup, token generation, interceptor validation, and protected endpoint testing.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Mastering JWT: Secure API Authentication with Spring Boot

JSON Web Token (JWT) is an open standard (RFC 7519) that provides a compact, self‑contained way to securely transmit information as a JSON object, signed with a secret or public/private key pair.

It is mainly used for authorization (e.g., Single Sign‑On) and secure information exchange, where the signature guarantees integrity and, when using asymmetric keys, authenticates the issuer.

JWT Structure

A JWT consists of three Base64Url‑encoded parts separated by dots: Header , Payload , and Signature (format header.payload.signature).

Header

The header specifies the token type and signing algorithm, e.g.:

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

The payload contains claims. Claims are divided into registered, public, and private types. Example payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

The signature is created by signing the encoded header and payload with a secret or private key, for example:

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secret
)

An example JWT looks like:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWRtaW4iLCJpZCI6IjEiLCJleHAiOjE2MDY5NzA0ODd9.uMB243IGMnms3KtYPqZR4JJQoXePdzdBg8X8uaOkISI

Using JWT in Spring Boot

Add the Auth0 Java JWT dependency:

<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.11.0</version>
</dependency>

Define an entity, repository, and service for user data, then create two REST endpoints: one for login that returns a token, and one protected resource.

Token generation utility:

public class JwtUtils {
    public static String genToken(Users users) {
        Builder builder = JWT.create();
        builder.withClaim("id", users.getId());
        builder.withClaim("name", users.getUsername());
        LocalDateTime ldt = LocalDateTime.now().plusMinutes(30);
        builder.withExpiresAt(Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant()));
        Algorithm algorithm = Algorithm.HMAC256("abc");
        return builder.sign(algorithm);
    }
}

A security interceptor extracts the token from the request header or parameter, verifies it, and throws an exception if it is missing or invalid.

public class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = extractToken(request);
        if (token == null) {
            throw new RuntimeException("Missing valid token");
        }
        JWTVerifier verify = JWT.require(Algorithm.HMAC256("abc")).build();
        verify.verify(token);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
    private String extractToken(HttpServletRequest request) {
        String token = request.getHeader("access-token");
        if (token == null) {
            token = request.getParameter("access-token");
        }
        return token;
    }
}

Register the interceptor for protected paths:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SecurityInterceptor()).addPathPatterns("/res/**");
    }
}

After starting the application, obtain a token via the /users/login endpoint, then include it in the access-token header when calling the protected /res/info endpoint.

JWT sign method diagram
JWT sign method diagram
JWT token generation steps
JWT token generation steps
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootAuthenticationJWTAPI Security
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.