An access token is a short-lived JWT the app sends with every API call to prove who the user is. A refresh token is a long-lived token kept only to get a new access token when the old one expires. When the access token expires, the app calls the refresh endpoint, and the user is never asked to log in again. A short access token limits damage if it is stolen, while the refresh token keeps the user signed in for days.
Features
- Login returns both an access token (1 minute here) and a refresh token (7 days)
- The access token is a signed JWT validated by a custom filter on every request
- The refresh token is a random UUID stored in MySQL, so it can be revoked
- Refresh token rotation: each refresh revokes the old token and issues a new one
- Logout revokes the refresh token
- A reused or revoked refresh token is rejected with
401 - Expired access tokens get a clear
401message so the app knows to refresh
Access Token vs Refresh Token
| Access Token | Refresh Token | |
|---|---|---|
| Purpose | Call protected APIs | Get a new access token |
| Format | Signed JWT | Random UUID stored in the database |
| Lifetime | Short (1 minute in the demo) | Long (7 days) |
| Sent to | Every protected API | Only /api/auth/refresh and /logout |
| Can be revoked? | No, it simply expires | Yes, it is stored in the database |
Token Renewal Flow
- Login returns an access token and a refresh token.
- The app calls wallet APIs with the access token.
- The access token expires and the API returns
401 Access token expired. - The app sends the refresh token to
POST /api/auth/refresh. - The server checks the refresh token (exists, not revoked, not expired), revokes it, and returns a new access token and a new refresh token.
- The app retries the wallet call with the new access token.
Hands-on Experiment: Building a Digital Wallet Application with Access Token and Refresh Token
Aim: Issue access and refresh tokens at login and renew an expired access token through a refresh endpoint, with no second login.
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 digital-wallet-app, Jar, Java 17. Dependencies: Spring Web, Spring Data JPA, Spring Security, Validation, MySQL Driver.
Step 2: Project structure
com.example.digitalwallet
├── entity → User, RefreshToken
├── repository → UserRepository, RefreshTokenRepository
├── service → JwtService, RefreshTokenService, JwtAuthenticationFilter,
│ SecurityConfig, AuthService, WalletService
└── controller → AuthController, WalletController
Step 3: Create the files according to the project structure
package com.example.digitalwallet.entity;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "wallet_users")
public class User {
@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, precision = 15, scale = 2)
private BigDecimal walletBalance;
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 BigDecimal getWalletBalance() { return walletBalance; }
public void setWalletBalance(BigDecimal walletBalance) { this.walletBalance = walletBalance; }
}
package com.example.digitalwallet.entity;
import jakarta.persistence.*;
import java.time.Instant;
@Entity
@Table(name = "refresh_tokens")
public class RefreshToken {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true, length = 100)
private String token;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(nullable = false)
private Instant expiryDate;
@Column(nullable = false)
private boolean revoked = false;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getToken() { return token; }
public void setToken(String token) { this.token = token; }
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Instant getExpiryDate() { return expiryDate; }
public void setExpiryDate(Instant expiryDate) { this.expiryDate = expiryDate; }
public boolean isRevoked() { return revoked; }
public void setRevoked(boolean revoked) { this.revoked = revoked; }
}
package com.example.digitalwallet.repository;
import com.example.digitalwallet.entity.RefreshToken;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByToken(String token);
}
package com.example.digitalwallet.repository;
import com.example.digitalwallet.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}
package com.example.digitalwallet.service;
import com.example.digitalwallet.entity.RefreshToken;
import com.example.digitalwallet.entity.User;
import com.example.digitalwallet.repository.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.util.Map;
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
private final RefreshTokenService refreshTokenService;
public AuthService(UserRepository userRepository,
PasswordEncoder passwordEncoder,
JwtService jwtService,
RefreshTokenService refreshTokenService) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.jwtService = jwtService;
this.refreshTokenService = refreshTokenService;
}
public User register(String name, String email, String password) {
if (userRepository.existsByEmail(email)) {
throw new ResponseStatusException(HttpStatus.CONFLICT, "Email already registered");
}
User user = new User();
user.setName(name);
user.setEmail(email);
user.setPassword(passwordEncoder.encode(password));
user.setWalletBalance(BigDecimal.ZERO);
return userRepository.save(user);
}
// Login gives BOTH tokens
public Map<String, Object> login(String email, String password) {
User user = userRepository.findByEmail(email)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid email or password"));
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid email or password");
}
RefreshToken refreshToken = refreshTokenService.create(user);
return tokenResponse(jwtService.generateAccessToken(user.getEmail()), refreshToken.getToken());
}
// Renew the access token without asking for the password again.
// Refresh token rotation: the old refresh token is revoked and a new one is issued.
@Transactional
public Map<String, Object> refresh(String refreshTokenValue) {
RefreshToken oldToken = refreshTokenService.verify(refreshTokenValue);
User user = oldToken.getUser();
refreshTokenService.revoke(oldToken);
RefreshToken newToken = refreshTokenService.create(user);
return tokenResponse(jwtService.generateAccessToken(user.getEmail()), newToken.getToken());
}
// Logout revokes the refresh token, so it can never renew access again
public void logout(String refreshTokenValue) {
RefreshToken refreshToken = refreshTokenService.verify(refreshTokenValue);
refreshTokenService.revoke(refreshToken);
}
private Map<String, Object> tokenResponse(String accessToken, String refreshToken) {
return Map.of(
"tokenType", "Bearer",
"accessToken", accessToken,
"refreshToken", refreshToken,
"accessTokenExpiresInMs", jwtService.getAccessExpirationMs());
}
}
package com.example.digitalwallet.service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
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.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.List;
// Validates the ACCESS token on every protected request.
// NOT a @Component: SecurityConfig creates it and adds it to the security chain.
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private final JwtService jwtService;
public JwtAuthenticationFilter(JwtService jwtService) {
this.jwtService = jwtService;
}
// register, login, refresh and logout are public
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return request.getServletPath().startsWith("/api/auth/");
}
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
try {
Claims claims = jwtService.parseClaims(header.substring(7));
if (SecurityContextHolder.getContext().getAuthentication() == null) {
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(
claims.getSubject(), null, List.of(new SimpleGrantedAuthority("ROLE_USER")));
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (ExpiredJwtException e) {
// The app should now call /api/auth/refresh with its refresh token
sendUnauthorized(response, "Access token expired");
return;
} catch (JwtException | IllegalArgumentException e) {
sendUnauthorized(response, "Invalid access token");
return;
}
chain.doFilter(request, response);
}
private void sendUnauthorized(HttpServletResponse response, String message) throws IOException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"error\":\"Unauthorized\",\"message\":\"" + message + "\"}");
}
}
package com.example.digitalwallet.service;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.util.Date;
// Creates and validates the short-lived ACCESS token (a JWT).
// The refresh token is NOT a JWT: it is a random value stored in the database.
@Service
public class JwtService {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.access-expiration-ms}")
private long accessExpirationMs;
private SecretKey signingKey() {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
}
public String generateAccessToken(String email) {
Date now = new Date();
return Jwts.builder()
.subject(email)
.issuedAt(now)
.expiration(new Date(now.getTime() + accessExpirationMs))
.signWith(signingKey())
.compact();
}
// Throws ExpiredJwtException / JwtException when the token is not acceptable
public Claims parseClaims(String token) {
return Jwts.parser()
.verifyWith(signingKey())
.build()
.parseSignedClaims(token)
.getPayload();
}
public long getAccessExpirationMs() {
return accessExpirationMs;
}
}
package com.example.digitalwallet.service;
import com.example.digitalwallet.entity.RefreshToken;
import com.example.digitalwallet.entity.User;
import com.example.digitalwallet.repository.RefreshTokenRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
import java.time.Instant;
import java.util.UUID;
@Service
public class RefreshTokenService {
@Value("${jwt.refresh-expiration-ms}")
private long refreshExpirationMs;
private final RefreshTokenRepository refreshTokenRepository;
public RefreshTokenService(RefreshTokenRepository refreshTokenRepository) {
this.refreshTokenRepository = refreshTokenRepository;
}
// Create a new random refresh token and store it
public RefreshToken create(User user) {
RefreshToken refreshToken = new RefreshToken();
refreshToken.setUser(user);
refreshToken.setToken(UUID.randomUUID().toString());
refreshToken.setExpiryDate(Instant.now().plusMillis(refreshExpirationMs));
refreshToken.setRevoked(false);
return refreshTokenRepository.save(refreshToken);
}
// Accept only tokens that exist, are not revoked and are not expired
public RefreshToken verify(String tokenValue) {
RefreshToken refreshToken = refreshTokenRepository.findByToken(tokenValue)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid refresh token"));
if (refreshToken.isRevoked()) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Refresh token already used or revoked");
}
if (refreshToken.getExpiryDate().isBefore(Instant.now())) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Refresh token expired, please login again");
}
return refreshToken;
}
public void revoke(RefreshToken refreshToken) {
refreshToken.setRevoked(true);
refreshTokenRepository.save(refreshToken);
}
}
package com.example.digitalwallet.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, JwtService jwtService) 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(new JwtAuthenticationFilter(jwtService), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
}
package com.example.digitalwallet.service;
import com.example.digitalwallet.entity.User;
import com.example.digitalwallet.repository.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
@Service
public class WalletService {
private final UserRepository userRepository;
public WalletService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getWallet(String email) {
return userRepository.findByEmail(email)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Wallet not found"));
}
@Transactional
public User addMoney(String email, BigDecimal amount) {
User user = getWallet(email);
user.setWalletBalance(user.getWalletBalance().add(amount));
return userRepository.save(user);
}
}
package com.example.digitalwallet.controller;
import com.example.digitalwallet.service.AuthService;
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;
public AuthController(AuthService authService) {
this.authService = authService;
}
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 RefreshRequest(@NotBlank String refreshToken) {
}
@PostMapping("/register")
public ResponseEntity<Map<String, Object>> register(@Valid @RequestBody RegisterRequest request) {
authService.register(request.name(), request.email(), request.password());
return ResponseEntity.status(HttpStatus.CREATED)
.body(Map.of("message", "Wallet account created successfully"));
}
@PostMapping("/login")
public Map<String, Object> login(@Valid @RequestBody LoginRequest request) {
return authService.login(request.email(), request.password());
}
@PostMapping("/refresh")
public Map<String, Object> refresh(@Valid @RequestBody RefreshRequest request) {
return authService.refresh(request.refreshToken());
}
@PostMapping("/logout")
public Map<String, Object> logout(@Valid @RequestBody RefreshRequest request) {
authService.logout(request.refreshToken());
return Map.of("message", "Logged out successfully");
}
}
package com.example.digitalwallet.controller;
import com.example.digitalwallet.entity.User;
import com.example.digitalwallet.service.WalletService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.Map;
@RestController
@RequestMapping("/api/wallet")
public class WalletController {
private final WalletService walletService;
public WalletController(WalletService walletService) {
this.walletService = walletService;
}
public record AddMoneyRequest(@NotNull @Positive BigDecimal amount) {
}
// Protected: needs a valid ACCESS token
@GetMapping("/balance")
public Map<String, Object> balance(Authentication authentication) {
User user = walletService.getWallet(authentication.getName());
return Map.of(
"name", user.getName(),
"email", user.getEmail(),
"balance", user.getWalletBalance());
}
// Protected: needs a valid ACCESS token
@PostMapping("/add-money")
public Map<String, Object> addMoney(Authentication authentication,
@Valid @RequestBody AddMoneyRequest request) {
User user = walletService.addMoney(authentication.getName(), request.amount());
return Map.of(
"message", "Money added successfully",
"balance", user.getWalletBalance());
}
}
package com.example.digitalwallet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DigitalWalletApplication {
public static void main(String[] args) {
SpringApplication.run(DigitalWalletApplication.class, args);
}
}
spring.application.name=digital-wallet-app
server.port=8080
# MySQL (database is created automatically)
spring.datasource.url=jdbc:mysql://localhost:3306/digital_wallet_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=vpheSdSYjhkduqqnVeOSNzTepA6XGuO1Fpvl3g9f0Io=
# Access token: 1 minute (short, so you can see it expire during the demo)
jwt.access-expiration-ms=60000
# Refresh token: 7 days
jwt.refresh-expiration-ms=604800000Code language: PHP (php)
Step 4: Run the DigitalWalletApplication


