Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Security

JWT Tokens in Micronaut

How JSON Web Tokens work and how Micronaut Security issues and validates them: header, claims, HS256 signatures, expiry, refresh tokens and runnable Java stand-ins.

After a user logs in, the server needs a cheap way to recognise them on every later request. A JSON Web Token (JWT) is a small signed string that carries the user's name, roles and an expiry time. The server can verify it with a key and does not need to look anything up in a session store, which makes it a good fit for stateless services and microservices.

The real Micronaut JWT module is read-only here. The runnable examples build and verify a real HS256 token using only the JDK, so you can see exactly what the framework does for you.

Anatomy of a JWT

A JWT has three Base64URL parts separated by dots: header.payload.signature.

  • The header names the algorithm, for example {"alg":"HS256","typ":"JWT"}.
  • The payload holds claims: sub (subject, the user), roles, iat (issued at), exp (expires at), and any custom data.
  • The signature is a keyed hash of header.payload. Change one character in the payload and the signature no longer matches.

The payload is only encoded, not encrypted. Anyone holding the token can read it, so never put passwords or sensitive personal data in it.

Three parts, two dots

Header Algorithm and type.
Payload Claims such as sub, roles and exp.
1 / 2

Enabling JWT in Micronaut

Add micronaut-security-jwt, choose bearer authentication and give the server a signing secret:

GROOVY
annotationProcessor("io.micronaut.security:micronaut-security-annotations")
implementation("io.micronaut.security:micronaut-security-jwt")
YAML
micronaut:
  security:
    authentication: bearer
    endpoints:
      login:
        enabled: true
    token:
      jwt:
        signatures:
          secret:
            generator:
              secret: "${JWT_GENERATOR_SIGNATURE_SECRET}"
              jws-algorithm: HS256
        generator:
          access-token:
            expiration: 3600          # seconds

Read the secret from an environment variable. It must be long and random (at least 256 bits for HS256). Anyone who knows it can mint valid tokens for any user.

With this configuration:

  1. POST /login runs your authentication provider and returns {"access_token":"...","token_type":"Bearer","username":"alice","roles":[...],"expires_in":3600}.
  2. The client sends Authorization: Bearer <token> on later requests.
  3. The JwtTokenValidator checks the signature and expiry, then rebuilds the Authentication, so @Secured("ROLE_EDITOR") works exactly as before.

Signature algorithms

HS256 uses one shared secret: simple, and fine when one service both issues and verifies. For several services that only verify, use an asymmetric algorithm such as RS256 or ES256: the issuer keeps a private key and publishes a public key, often as a JWKS document (a JSON list of public keys). Micronaut can fetch a remote JWKS URL and cache it:

YAML
micronaut:
  security:
    token:
      jwt:
        signatures:
          jwks:
            auth-server:
              url: https://auth.example.org/.well-known/jwks.json

Always require an algorithm you chose. The old trick of sending "alg":"none" must never be accepted; libraries used by Micronaut reject it.

Try it: build and verify an HS256 token

This program does by hand what the framework does: Base64URL encodes the parts and signs them with HMAC-SHA256. It uses a fixed secret and clock, so the output is deterministic.

Java Sign and verify a JWT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Expiry and refresh tokens

A stolen token works until it expires, so keep access tokens short-lived (minutes to an hour). To avoid making users log in constantly, issue a second, longer-lived refresh token. When the access token expires the client sends the refresh token to /oauth/access_token and receives a new access token.

YAML
micronaut:
  security:
    token:
      jwt:
        generator:
          access-token:
            expiration: 900            # 15 minutes
          refresh-token:
            secret: "${JWT_REFRESH_SECRET}"

Micronaut leaves the storage of refresh tokens to you through the RefreshTokenPersistence interface, because you decide where to keep them (database, Redis) and how to revoke them. Rotating the refresh token on every use and storing only a hash of it limits the damage of a leak.

Try it: refresh token rotation

This stand-in keeps a store of valid refresh tokens. Each use deletes the old one and issues a new one, so a replayed token is rejected.

Java Rotating refresh tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Where to keep tokens in a browser

A token in localStorage can be stolen by any injected script (XSS). A token in an HttpOnly, Secure, SameSite cookie cannot be read by scripts, which is why Micronaut also supports authentication: cookie for browser applications. Choose cookies for browser front ends and bearer headers for mobile apps and service-to-service calls.

Common mistakes

  • Treating the payload as secret. It is only encoded.
  • A weak or hard-coded secret in the repository.
  • Long-lived access tokens with no way to revoke them.
  • Not checking exp, iss (issuer) and aud (audience) when tokens come from another system.
  • Putting a whole user profile into the token; it grows every request.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the signature of a JWT protect against?

    The signature is a keyed hash. Changing the content invalidates it, but the content is still readable.
  2. 2. Which claim holds the expiry time?

    exp is the time after which the token must be rejected.
  3. 3. Why are access tokens kept short-lived?

    A stolen token is usable until it expires, so a short life limits the exposure.
  4. 4. When is RS256 better than HS256?

    With asymmetric keys, verifiers only need the public key, so they cannot mint tokens.

Summary

  • A JWT is header.payload.signature; it is signed, not encrypted.
  • Micronaut issues tokens at /login and validates them on every request, rebuilding the Authentication.
  • Keep the signing secret out of the repository, make access tokens short-lived and use refresh tokens with rotation.
  • Use asymmetric signatures and JWKS when many services verify.

Next: OAuth 2.0 and OpenID Connect