Spring Security JWT Authentication in Spring Boot 3 (Uptime Monitor Part 4)
Add stateless JWT authentication to a Spring Boot 3 API with Spring Security, jjwt 0.12, BCrypt and per-user data access. Part 4 of the UpCheck series.
Part 4 of the UpCheck series adds register and login, signs a JWT for every user, and makes sure each user only ever sees their own monitors.
- Part 1: Project setup with MySQL and Docker
- Part 2: Database design with Flyway and JPA
- Part 3: REST API, validation and error handling
- Part 4: Spring Security with JWT (you are here)
- Part 5: Scheduler with virtual threads
- Part 6: Incidents and email alerts
- Part 7: Uptime stats, pagination and retention
- Part 8: Testing, Docker and deployment
Spring Security with JWT authentication#
Today users can register and log in, every API call carries a JWT, and each user only ever sees their own monitors. The API stays stateless: no sessions, no cookies, so it scales to more servers without sticky sessions.
How the JWT flow works#
- The client sends email + password to
POST /api/auth/login. - Spring's
AuthenticationManagerchecks the BCrypt hash; we return a signed JWT valid for 24 hours. - The client sends
Authorization: Bearer <token>on every request. JwtAuthFilterverifies the signature and expiry, loads the user, and puts them in theSecurityContext.- Controllers receive the user through
@CurrentUser; a missing or bad token gets a 401 in Problem Details format.
The database is hit only at login and to load the user; the token itself is verified with the secret key, no session lookup needed.
Step 1: The principal and a handy annotation#
We don't put the JPA entity into the security context. A small immutable record is safer and avoids lazy-loading surprises.
package com.upcheck.security;
import com.upcheck.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.List;
public record UserPrincipal(Long id, String email, String password, String role) implements UserDetails {
public static UserPrincipal from(User user) {
return new UserPrincipal(user.getId(), user.getEmail(), user.getPassword(), user.getRole().name());
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of(new SimpleGrantedAuthority("ROLE_" + role));
}
@Override public String getUsername() { return email; }
@Override public String getPassword() { return password; }
}
package com.upcheck.security;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import java.lang.annotation.*;
/** Inject the logged-in UserPrincipal into a controller method. */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@AuthenticationPrincipal
public @interface CurrentUser {
}
package com.upcheck.security;
import com.upcheck.user.UserRepository;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class AppUserDetailsService implements UserDetailsService {
private final UserRepository userRepository;
public AppUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserPrincipal loadUserByUsername(String email) {
return userRepository.findByEmail(email.toLowerCase())
.map(UserPrincipal::from)
.orElseThrow(() -> new UsernameNotFoundException("User not found"));
}
}
Step 2: JwtService (jjwt 0.12)#
package com.upcheck.security;
import com.upcheck.config.AppProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
import java.util.Optional;
@Service
public class JwtService {
private final SecretKey key;
private final Duration expiration;
private final Clock clock;
public JwtService(AppProperties props, Clock clock) {
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(props.jwt().secret()));
this.expiration = props.jwt().expiration();
this.clock = clock;
}
public String generateToken(UserPrincipal user) {
Instant now = clock.instant();
return Jwts.builder()
.subject(user.email())
.claim("uid", user.id())
.issuedAt(Date.from(now))
.expiration(Date.from(now.plus(expiration)))
.signWith(key)
.compact();
}
/** The email inside a valid token, or empty when the token is invalid or expired. */
public Optional<String> extractEmail(String token) {
try {
Claims claims = Jwts.parser()
.verifyWith(key)
.clock(() -> Date.from(clock.instant()))
.build()
.parseSignedClaims(token)
.getPayload();
return Optional.ofNullable(claims.getSubject());
} catch (JwtException | IllegalArgumentException e) {
return Optional.empty();
}
}
public long expiresInSeconds() {
return expiration.toSeconds();
}
}
Generate a production secret with openssl rand -base64 48 and pass it as the JWT_SECRET environment variable. HS256 needs at least 256 bits; jjwt refuses shorter keys.
Step 3: The JWT filter#
package com.upcheck.security;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class JwtAuthFilter extends OncePerRequestFilter {
private static final String PREFIX = "Bearer ";
private final JwtService jwtService;
private final AppUserDetailsService userDetailsService;
public JwtAuthFilter(JwtService jwtService, AppUserDetailsService userDetailsService) {
this.jwtService = jwtService;
this.userDetailsService = userDetailsService;
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String header = request.getHeader(HttpHeaders.AUTHORIZATION);
if (header != null && header.startsWith(PREFIX)
&& SecurityContextHolder.getContext().getAuthentication() == null) {
jwtService.extractEmail(header.substring(PREFIX.length())).ifPresent(email -> {
try {
UserPrincipal user = userDetailsService.loadUserByUsername(email);
var auth = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (UsernameNotFoundException ignored) {
// token for a deleted user: stay anonymous, the entry point answers 401
}
});
}
chain.doFilter(request, response);
}
}
Step 4: Security configuration#
package com.upcheck.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ProblemDetail;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
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.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
@Configuration
public class SecurityConfig {
private static final String[] PUBLIC = {
"/api/auth/**",
"/actuator/health/**",
"/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**"
};
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthFilter jwtAuthFilter,
AuthenticationEntryPoint entryPoint) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable) // stateless API, no cookies
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers(PUBLIC).permitAll()
.anyRequest().authenticated())
.exceptionHandling(e -> e.authenticationEntryPoint(entryPoint))
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}
/** 401 in the same Problem Details format as every other error. */
@Bean
public AuthenticationEntryPoint authenticationEntryPoint(ObjectMapper mapper) {
return (request, response, ex) -> {
ProblemDetail pd = ProblemDetail.forStatusAndDetail(HttpStatus.UNAUTHORIZED,
"Missing or invalid access token");
pd.setTitle("Unauthorized");
response.setStatus(HttpStatus.UNAUTHORIZED.value());
response.setContentType(MediaType.APPLICATION_PROBLEM_JSON_VALUE);
mapper.writeValue(response.getOutputStream(), pd);
};
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}
Step 5: Register and login endpoints#
package com.upcheck.auth;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
public final class AuthDtos {
private AuthDtos() {}
public record RegisterRequest(
@NotBlank @Size(max = 100) String name,
@NotBlank @Email @Size(max = 255) String email,
@NotBlank @Size(min = 8, max = 72, message = "must be 8 to 72 characters") String password
) {}
public record LoginRequest(@NotBlank @Email String email, @NotBlank String password) {}
public record AuthResponse(String accessToken, String tokenType, long expiresIn) {}
}
Why max 72? BCrypt ignores everything after 72 bytes, so a longer limit would give users a false sense of security.
package com.upcheck.auth;
import com.upcheck.auth.AuthDtos.AuthResponse;
import com.upcheck.auth.AuthDtos.LoginRequest;
import com.upcheck.auth.AuthDtos.RegisterRequest;
import com.upcheck.common.exception.BusinessException;
import com.upcheck.security.JwtService;
import com.upcheck.security.UserPrincipal;
import com.upcheck.user.User;
import com.upcheck.user.UserRepository;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthenticationManager authenticationManager;
private final JwtService jwtService;
public AuthService(UserRepository userRepository, PasswordEncoder passwordEncoder,
AuthenticationManager authenticationManager, JwtService jwtService) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authenticationManager = authenticationManager;
this.jwtService = jwtService;
}
@Transactional
public AuthResponse register(RegisterRequest req) {
String email = req.email().trim().toLowerCase();
if (userRepository.existsByEmail(email)) {
throw new BusinessException(HttpStatus.CONFLICT, "Email is already registered");
}
User user = userRepository.save(
new User(req.name().trim(), email, passwordEncoder.encode(req.password())));
return tokenFor(UserPrincipal.from(user));
}
public AuthResponse login(LoginRequest req) {
// throws BadCredentialsException on a wrong email or password -> 401
Authentication auth = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(req.email().trim().toLowerCase(), req.password()));
return tokenFor((UserPrincipal) auth.getPrincipal());
}
private AuthResponse tokenFor(UserPrincipal user) {
return new AuthResponse(jwtService.generateToken(user), "Bearer", jwtService.expiresInSeconds());
}
}
package com.upcheck.auth;
import com.upcheck.auth.AuthDtos.*;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
@Tag(name = "Auth")
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public AuthResponse register(@Valid @RequestBody RegisterRequest request) {
return authService.register(request);
}
@PostMapping("/login")
public AuthResponse login(@Valid @RequestBody LoginRequest request) {
return authService.login(request);
}
}
Step 6: Try it with curl#
# register (returns a token)
curl -s -X POST localhost:8080/api/auth/register \
-H 'Content-Type: application/json' \
-d '{"name":"Sumit","email":"sumit@example.com","password":"Str0ngPass!"}'
# save the token
TOKEN=$(curl -s -X POST localhost:8080/api/auth/login \
-H 'Content-Type: application/json' \
-d '{"email":"sumit@example.com","password":"Str0ngPass!"}' | jq -r .accessToken)
# create a monitor
curl -s -X POST localhost:8080/api/monitors \
-H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
-d '{"name":"My blog","url":"https://example.com","intervalMinutes":1}'
# list my monitors
curl -s localhost:8080/api/monitors -H "Authorization: Bearer $TOKEN"
A request without a token returns 401, another user's monitor returns 404, and your own monitors return 200.
Key takeaways#
- A stateless API needs no sessions: verify the JWT signature and expiry on every request.
- Keep a small UserPrincipal record in the security context instead of the JPA entity.
- Return 401 in the same Problem Details format as every other error.