Spring Boot services · Chapter 30 of 41

Access and refresh tokens

By the end of this chapter you can keep access tokens short and still keep customers logged in for a week, with refresh tokens the server can take back. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Security
  • 5 tasks
  • Spring Boot
  • In the all labs plan

The first 2 chapters of Spring Boot services are free. This one comes with the all labs plan.

Why you need this

A JWT cannot be taken back: it works until it expires, whatever the server thinks. So a phone left logged in at Bengaluru station is a working key to Tapri Cloud for as long as its token lives. Kabir cut that to 15 minutes, and now Anjali's customers are logged out four times on one train journey.

Login today hands out only that short token:

$ curl -H "Content-Type: application/json" -d '{"username":"priya","password":"chai123"}' localhost:8081/auth/login
{"accessToken":"eyJhbGciOiJIUzM4NCJ9.eyJzdWIiOiJwcml5YSIsInJvbGVzIjpbIlJPTEVfVVNFUiJdLCJpYXQiOjE3OTEzNzkwMDgsImV4cCI6MTc5MTM3OTkwOH0.7nodWevYrZTvRwk3zRgChU0DOIPj4oUDx4NSGhwovTX1dUizfAfmfQAbI8oSEKxz","refreshToken":null}

Its payload is {"sub":"priya","roles":["ROLE_USER"],"iat":1791379008,"exp":1791379908}: 900 seconds. A longer life means a longer gift to a thief; a shorter one means more logins. One token cannot do both jobs.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    RefreshTokenService.java: a refresh token at login, stored as a hash

    Make RefreshTokenService.issue(user) also make a new refresh token value (newTokenValue), save a RefreshToken with hash(value), the user's name and an expiry exactly REFRESH_TOKEN_LIFETIME (7 days) after clock.instant(), and return Tokens with the access token and the refresh token value.

    POST /auth/login then answers 200 with a non-blank accessToken and refreshToken. The stored row's tokenHash equals hash of the returned value (never the value itself), and its status is ACTIVE. The access token still stops working 15 minutes later.

  2. Task 2

    RefreshTokenService.java: swap a refresh token for a new pair

    Write rotate(refreshToken): find the stored RefreshToken by hash(refreshToken), and when it is ACTIVE and not expired, mark it rotated and return a new pair from issue, for the user loaded again from the UserDetailsService by the stored username.

    Twenty minutes after login (the access token has expired), POST /auth/refresh with the refresh token answers 200 with a new pair: the new refresh token differs from the old one, the new access token works on GET /orders/mine, and the old refresh token's status is ROTATED. Needs task 1.

  3. Task 3 · interview question

    Interview: refuse a reused refresh token and revoke every token of that user

    In rotate, when the stored token is already ROTATED, revoke every ACTIVE refresh token of that user (findByUsernameAndStatus), then throw InvalidRefreshTokenException, which answers 401.

    After ravi refreshes once, sending his first refresh token again answers 401, he has no ACTIVE refresh tokens left, and the second refresh token (from the first refresh) answers 401 too, because it is now REVOKED and rotate refuses a REVOKED token. Needs tasks 1 and 2.

    Be ready to explain why the server refuses both the thief and the real user.

  4. Task 4

    RefreshTokenService.java: logout revokes one refresh token

    Write revoke(refreshToken) so the stored token with that value (looked up by its hash) becomes REVOKED when it is ACTIVE; a token that is not stored is ignored. Make rotate refuse a REVOKED token with InvalidRefreshTokenException (401).

    POST /auth/logout answers 204, a refresh with that token then answers 401, its status is REVOKED, and the same user's other refresh token (another login) still refreshes with 200. Needs tasks 1 and 2.

  5. Task 5

    RefreshTokenService.java: refuse expired and unknown refresh tokens

    Make rotate throw InvalidRefreshTokenException (401) for a token that was never issued (not-a-real-token) and for one at or after its expiry by clock.instant().

    A token refreshed 6 days after login still works and gives a new token that lives 7 days from then; 7 days and 1 minute later that new token answers 401. Needs tasks 1 and 2.

What you will learn

  • Two tokens, two jobs: a short access token checked by signature, and a long refresh token checked in the database.
  • Storing a hash: what the database keeps instead of the token.
  • Rotation and reuse detection: how a stolen refresh token gives itself away (the interview question).
  • Logout and time: revoking one token, and measuring expiry on the Clock.

More in Security

Build "Access and refresh tokens" yourself

Tapri Cloud: the counters’ Java grows into a Spring Boot service with a database. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Spring Boot services are free. This one comes with the all labs plan.