JWT Token Generation and Validation

Token generation creates a signed JWT after a customer logs in successfully. The token holds the customer’s email, name, role, issue time and expiry, all signed with a secret key. Token validation checks the signature and expiry on every request, so a tampered or expired token is rejected. This lets an online store keep its APIs stateless, with no server session per customer.

Features

  • Token generated at login with custom claims (name, role)
  • Signed with HMAC-SHA256 using a Base64 secret key
  • Configurable expiry (2 minutes here, so you can test expiry quickly)
  • Validation separates valid, expired, modified (bad signature) and malformed tokens
  • Public /validate endpoint that shows the token’s claims and remaining time
  • Protected shopping APIs that accept only valid tokens
  • BCrypt password hashing

Token Generation and Validation Steps

Generation (at login):

  1. Customer sends email and password.
  2. The password is checked against the BCrypt hash.
  3. JwtService builds the token (subject, claims, iat, exp) and signs it.
  4. The token is returned as Bearer.

Validation (on each request):

  1. JwtAuthenticationFilter reads the Authorization header.
  2. JwtService verifies the signature and expiry.
  3. If valid, the customer is marked authenticated.
  4. If not, the request gets 401.

Hands-on Experiment: Building an Online Shopping Authentication API with JWT Token Generation and Validation

Aim: Generate a JWT at login and validate it on every protected request, reporting whether a token is valid, expired or tampered with.

Software/Tools Required: JDK 17, Spring Boot 3.x, Maven, MySQL 8.x, IDE, Postman

Step 1: Generate the Project via Spring Initializr

Maven, Java, Spring Boot 3.3.x, Group com.example, Artifact online-shopping-auth, Jar, Java 17. Dependencies: Spring Web, Spring Data JPA, Spring Security, Validation, MySQL Driver.

Step 2: Project structure

com.example.shoppingauth
├── entity      → Customer
├── repository  → CustomerRepository
├── service     → JwtService, JwtAuthenticationFilter,
│                 SecurityConfig, AuthService, CustomerService
└── controller  → AuthController, ShopController

Step 3: Create the files according to the project structure

package com.example.shoppingauth.entity;

import jakarta.persistence.*;

@Entity
@Table(name = "customers")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    @Column(nullable = false)
    private String password;

    @Column(nullable = false)
    private String role;

    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }

    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password; }

    public String getRole() { return role; }
    public void setRole(String role) { this.role = role; }
}
package com.example.shoppingauth.repository;

import com.example.shoppingauth.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface CustomerRepository extends JpaRepository<Customer, Long> {

    Optional<Customer> findByEmail(String email);

    boolean existsByEmail(String email);
}
package com.example.shoppingauth.service;

import com.example.shoppingauth.entity.Customer;
import com.example.shoppingauth.repository.CustomerRepository;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

@Service
public class AuthService {

    private final CustomerRepository customerRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtService jwtService;

    public AuthService(CustomerRepository customerRepository,
                       PasswordEncoder passwordEncoder,
                       JwtService jwtService) {
        this.customerRepository = customerRepository;
        this.passwordEncoder = passwordEncoder;
        this.jwtService = jwtService;
    }

    public Customer register(String name, String email, String password) {
        if (customerRepository.existsByEmail(email)) {
            throw new ResponseStatusException(HttpStatus.CONFLICT, "Email already registered");
        }

        Customer customer = new Customer();
        customer.setName(name);
        customer.setEmail(email);
        customer.setPassword(passwordEncoder.encode(password));
        customer.setRole("CUSTOMER");

        return customerRepository.save(customer);
    }

    public Map<String, Object> login(String email, String password) {
        Customer customer = customerRepository.findByEmail(email)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid email or password"));

        if (!passwordEncoder.matches(password, customer.getPassword())) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid email or password");
        }

        String token = jwtService.generateToken(customer.getEmail(), customer.getName(), customer.getRole());

        return Map.of(
                "tokenType", "Bearer",
                "accessToken", token,
                "expiresInMs", jwtService.getExpirationMs());
    }
}
package com.example.shoppingauth.service;

import com.example.shoppingauth.entity.Customer;
import com.example.shoppingauth.repository.CustomerRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

@Service
public class CustomerService {

    private final CustomerRepository customerRepository;

    public CustomerService(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    public Customer getByEmail(String email) {
        return customerRepository.findByEmail(email)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Customer not found"));
    }
}
package com.example.shoppingauth.service;

import com.example.shoppingauth.repository.CustomerRepository;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final CustomerRepository customerRepository;

    public JwtAuthenticationFilter(JwtService jwtService, CustomerRepository customerRepository) {
        this.jwtService = jwtService;
        this.customerRepository = customerRepository;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {

        String header = request.getHeader("Authorization");

        if (header != null && header.startsWith("Bearer ")) {
            String token = header.substring(7);

            if (jwtService.isValid(token)) {
                String email = jwtService.extractEmail(token);

                customerRepository.findByEmail(email).ifPresent(customer -> {
                    UsernamePasswordAuthenticationToken authentication =
                            new UsernamePasswordAuthenticationToken(
                                    customer.getEmail(), null,
                                    List.of(new SimpleGrantedAuthority("ROLE_" + customer.getRole())));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                });
            }
        }

        chain.doFilter(request, response);
    }
}
package com.example.shoppingauth.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class JwtService {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration-ms}")
    private long expirationMs;

    private SecretKey signingKey() {
        return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    }

    // ---------- TOKEN GENERATION ----------
    public String generateToken(String email, String name, String role) {
        Date now = new Date();
        return Jwts.builder()
                .subject(email)                 // who the token belongs to
                .claim("name", name)            // custom claims
                .claim("role", role)
                .issuedAt(now)                  // iat
                .expiration(new Date(now.getTime() + expirationMs))   // exp
                .signWith(signingKey())         // HS256 signature
                .compact();
    }

    // ---------- TOKEN VALIDATION ----------
    public boolean isValid(String token) {
        try {
            readClaims(token);
            return true;
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }

    public String extractEmail(String token) {
        return readClaims(token).getSubject();
    }

    // Detailed validation result (used by the /validate endpoint)
    public Map<String, Object> inspect(String token) {
        Map<String, Object> result = new LinkedHashMap<>();
        try {
            Claims claims = readClaims(token);
            result.put("valid", true);
            result.put("subject", claims.getSubject());
            result.put("name", claims.get("name", String.class));
            result.put("role", claims.get("role", String.class));
            result.put("issuedAt", claims.getIssuedAt().toInstant().toString());
            result.put("expiresAt", claims.getExpiration().toInstant().toString());
            result.put("remainingSeconds",
                    (claims.getExpiration().getTime() - System.currentTimeMillis()) / 1000);
        } catch (ExpiredJwtException e) {
            result.put("valid", false);
            result.put("reason", "Token expired");
        } catch (SignatureException e) {
            result.put("valid", false);
            result.put("reason", "Invalid signature (token was modified)");
        } catch (MalformedJwtException e) {
            result.put("valid", false);
            result.put("reason", "Malformed token");
        } catch (JwtException | IllegalArgumentException e) {
            result.put("valid", false);
            result.put("reason", "Invalid token");
        }
        return result;
    }

    public long getExpirationMs() {
        return expirationMs;
    }

    private Claims readClaims(String token) {
        return Jwts.parser()
                .verifyWith(signingKey())
                .build()
                .parseSignedClaims(token)
                .getPayload();
    }
}
package com.example.shoppingauth.service;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http,
                                                   JwtAuthenticationFilter jwtFilter) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**", "/error").permitAll()
                .anyRequest().authenticated())
            .exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)))
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}
package com.example.shoppingauth.controller;

import com.example.shoppingauth.entity.Customer;
import com.example.shoppingauth.service.AuthService;
import com.example.shoppingauth.service.JwtService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final AuthService authService;
    private final JwtService jwtService;

    public AuthController(AuthService authService, JwtService jwtService) {
        this.authService = authService;
        this.jwtService = jwtService;
    }

    public record RegisterRequest(
            @NotBlank String name,
            @NotBlank @Email String email,
            @NotBlank @Size(min = 6, message = "Password must be at least 6 characters") String password) {
    }

    public record LoginRequest(
            @NotBlank @Email String email,
            @NotBlank String password) {
    }

    public record ValidateRequest(@NotBlank String token) {
    }

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody RegisterRequest request) {
        Customer customer = authService.register(request.name(), request.email(), request.password());
        return ResponseEntity.status(HttpStatus.CREATED).body(Map.of(
                "message", "Registration successful",
                "customerId", customer.getId()));
    }

    // Token generation
    @PostMapping("/login")
    public Map<String, Object> login(@Valid @RequestBody LoginRequest request) {
        return authService.login(request.email(), request.password());
    }

    // Token validation
    @PostMapping("/validate")
    public Map<String, Object> validate(@Valid @RequestBody ValidateRequest request) {
        return jwtService.inspect(request.token());
    }
}
package com.example.shoppingauth.controller;

import com.example.shoppingauth.entity.Customer;
import com.example.shoppingauth.service.CustomerService;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/shop")
public class ShopController {

    private final CustomerService customerService;

    public ShopController(CustomerService customerService) {
        this.customerService = customerService;
    }

    // Protected: needs "Authorization: Bearer <token>"
    @GetMapping("/profile")
    public Map<String, Object> profile(Authentication authentication) {
        Customer customer = customerService.getByEmail(authentication.getName());
        return Map.of(
                "name", customer.getName(),
                "email", customer.getEmail(),
                "role", customer.getRole());
    }

    // Protected: only authenticated customers can see the product list
    @GetMapping("/products")
    public List<Map<String, Object>> products() {
        return List.of(
                Map.of("id", 1, "name", "Wireless Mouse", "price", 799),
                Map.of("id", 2, "name", "Mechanical Keyboard", "price", 2499),
                Map.of("id", 3, "name", "USB-C Hub", "price", 1499));
    }
}
package com.example.shoppingauth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShoppingAuthApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShoppingAuthApplication.class, args);
    }
}
spring.application.name=online-shopping-auth
server.port=8080

# MySQL (database is created automatically)
spring.datasource.url=jdbc:mysql://localhost:3306/online_shopping_db?createDatabaseIfNotExist=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=password

spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

# JWT settings (secret is Base64, minimum 256 bits)
jwt.secret=iX9U4yv619ahYrVgl6T7KXqD5Qh+TcYzicD+ZvLJVHc=
# 2 minutes, so you can easily test token expiry
jwt.expiration-ms=120000Code language: PHP (php)

Step 4: Run the ShoppingAuthApplication

Scroll to Top