Skip to content
Visual explainer 8h to learn 5 steps

Spring Security & JWT auth

Secure endpoints with authentication and role-based access.

By Invicly Tech, , in Backend Java Development. About 11 minutes to read.

Topic 21 of 29

In short

Spring Security runs every request through a chain of filters that authenticate the caller and check permissions. With JWT, the client logs in once, then sends a signed token on each request.

Explained simply

Most APIs need two questions answered on every request. Who is calling? And is this caller allowed to do this? The first is authentication (proving identity). The second is authorization (checking permission). Spring Security answers both before your controller code ever runs.

It works like a row of guards at a door. Each request passes a line of small checks called filters. One filter reads the login token, another checks the rules for that URL, another turns failures into the right HTTP error. If any guard says no, the request stops and your controller never sees it.

Passwords need special care. You never store the password itself. You store a hash, a one-way scrambled version made with BCrypt. At login, Spring hashes what the user typed and compares the two. If your database leaks, attackers get hashes that are slow and expensive to crack.

For APIs used by mobile apps and single-page web apps, a common pattern is JWT (JSON Web Token). The user logs in once and receives a signed token. They send it in the Authorization header on every request. The server checks the signature and the expiry time, and knows who the user is without a session.

Press Play on a diagram to walk through it one step at a time.

SequenceJWT login and an authorised call
Client
Auth endpoint
JWT filter
Controller
  1. 1POST /auth/login username, password
    Client to Auth endpoint: POST /auth/login username, password
  2. 2BCrypt hash matches: signed JWT returned
    Auth endpoint to Client: BCrypt hash matches: signed JWT returned
  3. 3GET /orders, Authorization: Bearer token
    Client to JWT filter: GET /orders, Authorization: Bearer token
  4. 4signature valid: set SecurityContext
    JWT filter to Controller: signature valid: set SecurityContext
  5. 5200 OK with orders
    Controller to Client: 200 OK with orders
FlowSecurity filter chain
  1. 1
    Request in

    Every HTTP request enters the chain

  2. 2
    CORS and CSRF filters

    Cross-origin and forgery protections

  3. 3
    Authentication filter

    Reads the JWT and identifies the user

  4. 4
    Authorization check

    Rules like hasRole ADMIN; else 401 or 403

  5. 5
    Controller

    Runs only if every filter passes

MapSpring Security building blocks
Spring Security
  • Filter chain
    • FilterChainProxy
    • SecurityFilterChain beans
    • ExceptionTranslationFilter
  • Authentication
    • AuthenticationManager
    • DaoAuthenticationProvider
    • UserDetailsService
  • Passwords
    • PasswordEncoder
    • BCryptPasswordEncoder
    • DelegatingPasswordEncoder
  • Tokens
    • JwtEncoder
    • JwtDecoder
    • oauth2ResourceServer
  • Authorization
    • authorizeHttpRequests
    • hasRole, hasAuthority
    • @PreAuthorize

In depth

How the filter chain is wired into the server

The servlet container (Tomcat) knows nothing about Spring beans. Spring Boot registers one servlet filter, DelegatingFilterProxy, which hands each request to a Spring bean called FilterChainProxy. That bean holds one or more SecurityFilterChain objects you define with @Bean. For each request it picks the first chain whose matcher fits the URL and runs only that chain's filters.

This lets you have different rules for different parts of the app, for example a stateless JWT chain for /api/** and a form-login chain for /admin/**. Use securityMatcher on each chain and @Order to control which is checked first. Near the end of every chain, ExceptionTranslationFilter catches security errors: an AuthenticationException becomes 401 through the AuthenticationEntryPoint, and an AccessDeniedException becomes 403 through the AccessDeniedHandler. AuthorizationFilter, the last one, applies your URL rules.

LayersWhere Spring Security sits in a request
  1. 1
    Tomcat

    Receives the HTTP request

  2. 2
    DelegatingFilterProxy

    Plain servlet filter that bridges to Spring

  3. 3
    FilterChainProxy

    Picks the first matching SecurityFilterChain

  4. 4
    Security filters

    CORS, CSRF, token reading, exception translation

  5. 5
    AuthorizationFilter

    Applies URL rules: permit, deny, hasRole

  6. 6
    DispatcherServlet and controller

    Your code, reached only if allowed

Authentication with a user store

A login check has three parts. AuthenticationManager (usually ProviderManager) receives a username and password token. It asks its providers; for passwords that is DaoAuthenticationProvider. That provider calls your UserDetailsService.loadUserByUsername to fetch the stored user, then PasswordEncoder.matches to compare the typed password with the stored hash.

You supply the UserDetailsService, typically a small class that loads a user entity with a JPA repository and returns a UserDetails with the hash and authorities. If the user is not found, throw UsernameNotFoundException; Spring reports it as bad credentials, so attackers cannot tell which usernames exist. On success the result is an authenticated Authentication object, which is stored in the SecurityContext for the rest of the request.

SequenceWhat happens inside authenticate()
Login endpoint
AuthenticationManager
UserDetailsService
PasswordEncoder
  1. 1authenticate(username, password)
    Login endpoint to AuthenticationManager: authenticate(username, password)
  2. 2loadUserByUsername(username)
    AuthenticationManager to UserDetailsService: loadUserByUsername(username)
  3. 3UserDetails: hash and roles
    UserDetailsService to AuthenticationManager: UserDetails: hash and roles
  4. 4matches(typed, storedHash)
    AuthenticationManager to PasswordEncoder: matches(typed, storedHash)
  5. 5true
    PasswordEncoder to AuthenticationManager: true
  6. 6Authenticated, with authorities
    AuthenticationManager to Login endpoint: Authenticated, with authorities

BCrypt: what the stored hash really contains

A BCrypt hash looks like $2a$10$ followed by 53 characters, 60 in total. The 10 is the cost factor: the algorithm runs 2 to the power of 10 rounds. Each extra point doubles the work, so cost 12 takes about four times longer than 10. Spring's BCryptPasswordEncoder uses 10 by default. Aim for a login check that takes a few hundred milliseconds on your servers.

The next 22 characters are a random salt, made fresh for every password. Two users with the same password get different hashes, so precomputed tables are useless. Note that BCrypt only uses the first 72 bytes of the input. For future upgrades, PasswordEncoderFactories.createDelegatingPasswordEncoder() stores a prefix such as {bcrypt} so you can later switch algorithms and still verify old hashes.

  • new BCryptPasswordEncoder(12) raises the cost factor
  • Never compare hashes yourself; use encoder.matches(raw, hash)
  • Spring Security 6.3+ can also check passwords against known breach lists

Issuing and validating JWTs

A JWT has three base64url parts separated by dots: a header (the algorithm), a payload of claims, and a signature. Standard claims include sub (the user), iat (issued at), exp (expiry), iss (issuer) and aud (audience). Anyone can decode the payload, so it must never hold secrets.

With HS256 the same secret signs and verifies; it must be at least 256 bits and come from configuration, not source code. With RS256 a private key signs and any service can verify with the public key, which suits many services. You do not need to write your own filter: add spring-boot-starter-oauth2-resource-server and call oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())). Spring then validates the signature, exp and nbf on every request. Keep access tokens short-lived (5 to 15 minutes) and use refresh tokens for longer sessions, because a signed JWT cannot easily be revoked before it expires.

  • spring.security.oauth2.resourceserver.jwt.issuer-uri points at a real identity provider
  • By default the scope claim becomes SCOPE_ authorities; map a roles claim yourself
  • Return 401 with WWW-Authenticate: Bearer when the token is missing or invalid

Role-based access rules

URL rules in authorizeHttpRequests are checked top to bottom and the first match wins, so put specific paths before general ones and finish with anyRequest().authenticated(). hasRole("ADMIN") checks for the authority ROLE_ADMIN; hasAuthority("orders:write") checks the exact string. Roles are coarse groups; authorities can be fine-grained permissions.

URL rules cannot see the data. For rules like "users may only read their own orders", add @EnableMethodSecurity and use @PreAuthorize on service methods, for example @PreAuthorize("hasRole('ADMIN')"), or simply query by owner: findByIdAndOwner(id, currentUser). Many APIs return 404 instead of 403 for other people's resources, so they do not reveal that the record exists.

Learn it in 5 short steps

About 1h 35m each. Track them with a timer in your plan.

  1. 1
    Learn the security filter chain~1h 35m
  2. 2
    Configure authentication with a user store~1h 35m
  3. 3
    Hash passwords with BCrypt~1h 35m
  4. 4
    Issue and validate JWTs~1h 35m
  5. 5
    Add role-based access to endpoints~1h 35m

Key points

  • Authentication answers who you are; authorization answers what you may do.
  • Store only BCrypt hashes of passwords, never plain text.
  • JWTs are signed, not encrypted; never put secrets in the payload.
  • 401 means not authenticated; 403 means authenticated but not allowed.

Key terms

Tap a card to flip it. 0/5 known

Examples

java
@Bean
SecurityFilterChain api(HttpSecurity http, JwtFilter jwtFilter) throws Exception {
  return http
      .csrf(csrf -> csrf.disable())  // stateless token API
      .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
      .authorizeHttpRequests(auth -> auth
          .requestMatchers("/auth/**").permitAll()
          .requestMatchers("/admin/**").hasRole("ADMIN")
          .anyRequest().authenticated())
      .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
      .build();
}

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

A login endpoint that issues a 15-minute JWT

Step 1: expose the AuthenticationManager as a bean and inject a JwtEncoder (for HS256, a NimbusJwtEncoder built from your secret key). Step 2: authenticate the username and password; a wrong password throws and becomes 401. Step 3: build claims with subject, expiry and roles. Step 4: sign and return the token. Clients then send Authorization: Bearer followed by the token, and the resource server config validates it on each call.

java
@PostMapping("/auth/login")
TokenResponse login(@RequestBody LoginRequest req) {
  Authentication auth = authManager.authenticate(
      UsernamePasswordAuthenticationToken.unauthenticated(req.username(), req.password()));
  Instant now = Instant.now();
  JwtClaimsSet claims = JwtClaimsSet.builder()
      .issuer("bookings-api").subject(auth.getName())
      .issuedAt(now).expiresAt(now.plus(15, ChronoUnit.MINUTES))
      .claim("roles", auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).toList())
      .build();
  JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();
  return new TokenResponse(jwtEncoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue());
}

Users can only see their own bookings

The URL rule /api/bookings/** requires login, but any logged-in user could still guess another booking id. Step 1: read the current user from the Authentication argument (Spring injects it into controller methods). Step 2: load the booking by id and owner in one query. Step 3: if nothing comes back, return 404, so the API does not reveal that the id exists. Admins get a separate endpoint protected with hasRole.

java
@GetMapping("/api/bookings/{id}")
BookingDto get(@PathVariable Long id, Authentication auth) {
  return bookings.findByIdAndOwnerUsername(id, auth.getName())
      .map(BookingDto::from)
      .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}

@PreAuthorize("hasRole('ADMIN')")
@GetMapping("/api/admin/bookings")
List<BookingDto> all() { return bookings.findAll().stream().map(BookingDto::from).toList(); }

Quick reference

  • 401 = not authenticated (who are you?); 403 = authenticated but not allowed
  • hasRole("ADMIN") checks the authority ROLE_ADMIN; hasAuthority checks the exact string
  • URL rules match top to bottom: specific paths first, anyRequest() last
  • BCryptPasswordEncoder default cost is 10; each +1 doubles the hashing time
  • JWT payloads are only base64url encoded: anyone can read them
  • HS256 secrets need at least 256 bits and belong in config or a vault, not code
  • @EnableMethodSecurity turns on @PreAuthorize for service methods
  • Stateless token APIs usually disable CSRF; cookie session apps must keep it

Common mistakes

  • Hard-coding the JWT signing key in source code.
  • Issuing tokens with no expiry.
  • Disabling CSRF on a cookie-based session app, where it is still needed.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Which component turns an AccessDeniedException into a 403 response?

Question 2

2Two users choose the same password. Why are their BCrypt hashes different?

Question 3

3A rule list has anyRequest().authenticated() first, then requestMatchers("/public/**").permitAll(). What happens?

Question 4

4Why keep JWT access tokens short-lived?

Question 5

5What does UsernameNotFoundException become in the HTTP response by default?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Hash the password secret123 with BCrypt cost 12, print the hash, and check that matches works for the right password and fails for a wrong one.

  2. Exercise 2medium

    Write a UserDetailsService that loads users from a JPA UserRepository with a role column such as ADMIN or USER.

  3. Exercise 3hard

    Your JWTs carry a roles claim like ["ROLE_ADMIN"]. Configure the resource server so hasRole("ADMIN") works.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I store the JWT in localStorage or a cookie?
localStorage is readable by any script, so an XSS bug can steal the token. An HttpOnly, Secure, SameSite cookie hides it from scripts, but then you need CSRF protection. Many teams use short access tokens in memory plus a refresh token in an HttpOnly cookie.
Why does my new Spring Boot app ask for a password on every page?
With spring-boot-starter-security on the classpath and no config of your own, Boot secures everything and prints a generated password for the user named user at startup. Define your own SecurityFilterChain bean to set real rules.
Do I need to write my own JWT filter?
Usually not. The OAuth2 resource server starter validates bearer tokens for you; you only configure the decoder and how claims map to authorities.
What is the difference between a role and an authority?
Both are GrantedAuthority strings. A role is just an authority with the ROLE_ prefix, and hasRole adds that prefix for you.

Go deeper

ShareXLinkedInWhatsApp