Skip to lesson

Login endpoint that returns a token

A customer should type the password once, not on every request. The API needs a login URL that checks the e-mail and password and hands back something the app can send instead.

The resource server starter and a JwtEncoder bean

JwtEncoder is the Spring Security interface that turns a set of claims into a signed JWT. ShopLite uses its Nimbus implementation with one HMAC key.

Hand-written signing code, as in the last lesson, is easy to get almost right. One starter gives ShopLite a tested encoder and decoder, and the encoder bean needs only the key.

Java
@Configuration@EnableConfigurationProperties(JwtProperties.class)class JwtConfig {
    @Bean    JwtEncoder jwtEncoder(JwtProperties properties) {        return NimbusJwtEncoder.withSecretKey(properties.signingKey())                .algorithm(MacAlgorithm.HS256)                .build();    }}

Example 1 · pom.xml: the resource server starter

Runs in: the shoplite-api Spring Boot project

XML
<!-- pom.xml: next to spring-boot-starter-security --><!-- JWT: Spring Security's resource server support (Nimbus JOSE + JWT inside). No version: Boot 4.1.1 manages it. --><dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId></dependency>
Sample output
$ mvn dependency:tree -Dincludes=com.nimbusds,org.springframework.security
...
com.shoplite:shoplite-api:jar:1.0.0
+- org.springframework.boot:spring-boot-starter-security:jar:4.1.1:compile
|  \- org.springframework.boot:spring-boot-security:jar:4.1.1:compile
|     +- org.springframework.security:spring-security-config:jar:7.1.1:compile
|     |  \- org.springframework.security:spring-security-core:jar:7.1.1:compile
|     |     \- org.springframework.security:spring-security-crypto:jar:7.1.1:compile
|     \- org.springframework.security:spring-security-web:jar:7.1.1:compile
+- org.springframework.boot:spring-boot-starter-oauth2-resource-server:jar:4.1.1:compile
|  \- org.springframework.boot:spring-boot-security-oauth2-resource-server:jar:4.1.1:compile
|     +- org.springframework.security:spring-security-oauth2-jose:jar:7.1.1:compile
|     |  +- org.springframework.security:spring-security-oauth2-core:jar:7.1.1:compile
|     |  \- com.nimbusds:nimbus-jose-jwt:jar:10.9.1:compile
|     \- org.springframework.security:spring-security-oauth2-resource-server:jar:7.1.1:compile
\- org.springframework.boot:spring-boot-starter-security-test:jar:4.1.1:test
   \- org.springframework.boot:spring-boot-security-test:jar:4.1.1:test
      \- org.springframework.security:spring-security-test:jar:7.1.1:test

What this code does

  • One starter brings Spring Security's JWT modules and Nimbus; the versions come from the Spring Boot 4.1.1 parent.
  • There is no jjwt anywhere: the encoder and decoder are Spring Security classes backed by Nimbus.

spring-boot-starter-oauth2-resource-server is Spring Security's own JWT support. It brings the Nimbus JOSE + JWT library, which does the Base64URL, the JSON and the HMAC, plus the interfaces JwtEncoder and JwtDecoder. There is no version in the pom.xml: Spring Boot 4.1.1 manages it. Tutorials that add jjwt do the same job with another library; ShopLite stays with what Spring Security ships.

JwtProperties reads the secret from the JWT_SECRET environment variable (the Expiry and signing keys lesson builds it in full); for now properties.signingKey() returns an HMAC-SHA256 key of 32 bytes.

The starter name says "resource server" because that is the OAuth 2 word for an API that accepts tokens. ShopLite is also its own login server here, which is fine for one API; a separate login server is the RS256 case from the last lesson.

POST /api/v1/auth/login and the AuthenticationManager

AuthenticationManager is the Spring Security object that checks credentials. It receives an unauthenticated e-mail and password and returns a trusted Authentication, or throws an AuthenticationException.

The password check is security-critical, so ShopLite does not compare hashes itself. It builds one manager from a DaoAuthenticationProvider and calls it from the login service.

Java
/** Checks an e-mail and password for the login endpoint. In SecurityConfig. */@BeanAuthenticationManager authenticationManager(UserDetailsService users, PasswordEncoder passwordEncoder) {    DaoAuthenticationProvider provider = new DaoAuthenticationProvider(users);    provider.setPasswordEncoder(passwordEncoder);    return new ProviderManager(provider);}
// in the authorizeHttpRequests rules:.requestMatchers(HttpMethod.POST, "/api/v1/auth/register", "/api/v1/auth/login").permitAll()

Example 2 · src/main/java/com/shoplite/auth/AuthService.java

Runs in: the shoplite-api Spring Boot project

AuthService.javaJava
package com.shoplite.auth;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.security.authentication.AuthenticationManager;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.stereotype.Service;
import com.shoplite.user.UserPrincipal;
/** Sign-in: check the e-mail and password, then hand out a signed access token. */@Servicepublic class AuthService {
    private static final Logger log = LoggerFactory.getLogger(AuthService.class);
    private final AuthenticationManager authenticationManager;    private final TokenService tokenService;
    AuthService(AuthenticationManager authenticationManager, TokenService tokenService) {        this.authenticationManager = authenticationManager;        this.tokenService = tokenService;    }
    /** Throws an AuthenticationException (401) for a wrong e-mail, a wrong password or a disabled account. */    public TokenResponse login(LoginRequest request) {        Authentication result = authenticationManager.authenticate(                UsernamePasswordAuthenticationToken.unauthenticated(request.email(), request.password()));        UserPrincipal user = (UserPrincipal) result.getPrincipal();        log.info("User {} signed in", user.getId());        return TokenResponse.bearer(tokenService.createAccessToken(user), tokenService.accessTokenSeconds());    }}
Note
AuthService has no main method; it runs inside the app. Example 4 calls it through POST /api/v1/auth/login.

What this code does

  • UsernamePasswordAuthenticationToken.unauthenticated(email, password) is the request; authenticate returns a new, trusted Authentication or throws.
  • The principal is the Users module's UserPrincipal, so the service gets the user id, customer id and roles without another query.
  • No password check, hash comparison or JSON here: each job lives in the class made for it.

The DaoAuthenticationProvider loads the user with the Users module's DatabaseUserDetailsService (by e-mail, from app_user and user_role) and compares the password with the BCrypt PasswordEncoder. It also checks the enabled flag, erases the password from memory after use, and for an unknown e-mail still runs one BCrypt check, so a wrong e-mail takes as long as a wrong password and timing does not reveal which e-mails exist.

AuthController (moved to the new com.shoplite.auth package, together with the Users module's register) only parses the body; AuthService calls the manager and asks TokenService for a token. The login URL must be in the permitAll list, or nobody could ever get a first token.

Order of execution

Put one login in order

Drag the steps into the order in which a login request is handled.

A TokenService that builds the JwtClaimsSet

JwtClaimsSet is the payload of a JWT as a Java object. Standard claims have named methods (issuer, subject, issuedAt, expiresAt) and custom claims use claim(name, value).

A token's contents follow rules: who the subject is, which roles, when it ends. ShopLite keeps every rule in one TokenService class; the code below builds the claims and signs them.

Example 3 · src/main/java/com/shoplite/auth/TokenService.java

Runs in: the shoplite-api Spring Boot project

TokenService.javaJava
package com.shoplite.auth;
import java.time.Clock;import java.time.Instant;import java.util.List;
import org.springframework.security.core.GrantedAuthority;import org.springframework.security.oauth2.jose.jws.MacAlgorithm;import org.springframework.security.oauth2.jwt.JwsHeader;import org.springframework.security.oauth2.jwt.JwtClaimsSet;import org.springframework.security.oauth2.jwt.JwtEncoder;import org.springframework.security.oauth2.jwt.JwtEncoderParameters;import org.springframework.stereotype.Service;
import com.shoplite.user.UserPrincipal;
/** Builds and signs access tokens. It never checks passwords: the caller has already done that. */@Servicepublic class TokenService {
    private final JwtEncoder encoder;    private final JwtProperties properties;    private final Clock clock;
    TokenService(JwtEncoder encoder, JwtProperties properties, Clock clock) {        this.encoder = encoder;        this.properties = properties;        this.clock = clock;    }
    /** A signed JWT for this user. Only ids and roles go in: the payload is readable by anyone. */    public String createAccessToken(UserPrincipal user) {        Instant now = clock.instant();        List<String> roles = user.getAuthorities().stream()                .map(GrantedAuthority::getAuthority)                .filter(authority -> authority.startsWith("ROLE_"))                .map(authority -> authority.substring("ROLE_".length()))                .toList();        JwtClaimsSet.Builder claims = JwtClaimsSet.builder()                .issuer(properties.issuer())                .subject(String.valueOf(user.getId()))      // the user id, not the e-mail                .issuedAt(now)                .expiresAt(now.plus(properties.accessTokenTtl()))                .claim("roles", roles);        if (user.getCustomerId() != null) {            claims.claim("customerId", user.getCustomerId());        }        JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build();        return encoder.encode(JwtEncoderParameters.from(header, claims.build())).getTokenValue();    }
    /** Seconds until a new access token expires, for the expiresIn field of the response. */    public long accessTokenSeconds() {        return properties.accessTokenTtl().toSeconds();    }}
Sample output
Decoded payload of a token it made for Asha (user 2, customer 1):
{"iss":"shoplite-api","customerId":1,"sub":"2","exp":1792138111,"iat":1792137211,"roles":["CUSTOMER"]}

And for the admin (user 1, no customer row):
{"iss":"shoplite-api","sub":"1","exp":1792138115,"iat":1792137215,"roles":["ADMIN"]}

What this code does

  • exp minus iat is 900 seconds: accessTokenTtl is 15 minutes.
  • The ROLE_ prefix is a Spring Security convention, so the token carries plain CUSTOMER and the decoder adds the prefix back in the next lesson.
  • The admin has no customerId claim, because the claim is added only when the account has a customer row.

JwtEncoder.encode adds the header, signs, and returns a Jwt whose getTokenValue() is the eyJ... text. The header is set with JwsHeader.with(MacAlgorithm.HS256), and the encoder also adds a kid (key id), a fingerprint of the key that a decoder can use later to pick the right key.

The subject is the user id, not the e-mail, because the payload is readable. roles lists the role names without the ROLE_ prefix, customerId is added only for customer accounts, and exp is now plus the configured 15 minutes. The time comes from an injected Clock, so a test can fix it.

The TokenResponse record

TokenResponse is the JSON record a successful login returns: accessToken, tokenType and expiresIn. The names follow the OAuth 2 token response, so many client libraries understand them without extra code.

After a login the app needs the token and a hint of how long it lasts. A small record holds those three fields.

TokenResponse.javaJava
/** What a successful login returns. expiresIn is in seconds, as in OAuth 2 token responses. */public record TokenResponse(String accessToken, String tokenType, long expiresIn) {
    static TokenResponse bearer(String accessToken, long expiresIn) {        return new TokenResponse(accessToken, "Bearer", expiresIn);    }}

Example 4 · Logging in with curl

Runs in: the shoplite-api Spring Boot project

Terminal
$ curl -i -X POST http://localhost:8080/api/v1/auth/login \       -H "Content-Type: application/json" \       -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}'
Sample output
HTTP/1.1 200
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json
Content-Length: 326
Date: Fri, 16 Oct 2026 07:53:32 GMT

{"accessToken":"eyJraWQiOiJVVWFwcy1CaDlC...hihs80","tokenType":"Bearer","expiresIn":900}

Server log:
... INFO 13912 --- [shoplite-api] [io-8080-exec-1] com.shoplite.auth.AuthService            : User 2 signed in

What this code does

  • The body is exactly the TokenResponse record: token, Bearer, 900 seconds. The token is shortened with ... here; yours is about 300 characters.
  • Cache-Control: no-store (added by Spring Security) tells browsers and proxies not to keep the response that holds the token.
  • The log says which user signed in by id, never the password.

tokenType is always Bearer, the word the client puts before the token in the header, and expiresIn is the number of seconds until expiry (900 for 15 minutes). The client needs expiresIn so it can plan a refresh without decoding the token.

The Refresh tokens lesson adds a fourth field, refreshToken; adding a field is not a breaking change in the contract.

Bad credentials: one generic 401

A failed login must not tell an attacker which part was wrong. One handler turns every failure into the same 401 answer.

Java
/** In GlobalExceptionHandler: wrong e-mail, wrong password or disabled account, one answer. */@ExceptionHandler(AuthenticationException.class)public ProblemDetail handleFailedLogin(AuthenticationException ex) {    log.info("Login failed: {}", ex.getClass().getSimpleName());    return ProblemKind.UNAUTHORIZED.problem("The e-mail or password is wrong.");}

Example 5 · Three failed logins

Runs in: the shoplite-api Spring Boot project

Terminal
# 1. right e-mail, wrong passwordcurl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \     -d '{"email":"asha.rao@example.com","password":"asha-wrong-password"}'# 2. e-mail with no accountcurl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \     -d '{"email":"nobody@example.com","password":"asha-dev-password"}'# 3. empty fieldscurl -i -X POST http://localhost:8080/api/v1/auth/login -H "Content-Type: application/json" \     -d '{"email":"","password":""}'
Sample output
HTTP/1.1 401
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The e-mail or password is wrong.","instance":"/api/v1/auth/login"}

HTTP/1.1 401
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/unauthorized","title":"Unauthorized","status":401,"detail":"The e-mail or password is wrong.","instance":"/api/v1/auth/login"}

HTTP/1.1 400
Content-Type: application/problem+json

{"type":"https://shoplite.example/problems/validation-failed","title":"Validation failed","status":400,"detail":"The request has 2 invalid fields.","instance":"/api/v1/auth/login","errors":[{"field":"email","message":"is required"},{"field":"password","message":"is required"}]}

Server log:
... INFO ... c.s.common.GlobalExceptionHandler        : Login failed: BadCredentialsException
... INFO ... c.s.common.GlobalExceptionHandler        : Login failed: BadCredentialsException

What this code does

  • A wrong password and an unknown e-mail give byte-for-byte the same 401 body, so the answer reveals nothing about which accounts exist.
  • Empty fields fail Bean Validation first (400 validation-failed) and never reach the AuthenticationManager.
  • Security headers are trimmed here; the 401s are application/problem+json like every other ShopLite error.

When the check fails, the manager throws an AuthenticationException: BadCredentialsException for a wrong password and also for an unknown e-mail (the provider hides UsernameNotFoundException on purpose), DisabledException for a disabled account. "No account with this e-mail" would tell an attacker which e-mails to try, and "account disabled" would confirm that the account exists, so every answer is "The e-mail or password is wrong." The log line keeps the real exception name for you, without the e-mail or password.

This handler works because the exception is thrown inside a controller call. Errors raised in the security filters (a missing or broken token) never reach @RestControllerAdvice; the next lesson handles those.

The contract gains two problem kinds in this section: unauthorized (401, title "Unauthorized") and forbidden (403, title "Forbidden"). Both are new constants in ProblemKind.

Next step

Check your understanding

11 quick questions