Skip to content
javahacks.dev
Micronaut

How to Use Micronaut Security With JWT Bearer Tokens

Secure a Micronaut API with JWT bearer tokens: configure signing, issue a token from a login endpoint and protect routes with annotations and roles.

6 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security, OpenJDK, OWASP and Keycloak logos.

Micronaut Security can protect an API with signed JWT bearer tokens in about forty lines of configuration and one class. The framework validates the token on every request, so the controller sees an authenticated user or never runs. This post builds the whole path on Micronaut 4: dependencies, a signing secret, a class that checks credentials, a protected controller, and the token lifetime decisions that matter once real users hold tokens. Examples use JDK 25.

Dependencies and configuration

Add the JWT module and the annotation processor for the security annotations.

pom.xmlXML
<dependency>
  <groupId>io.micronaut.security</groupId>
  <artifactId>micronaut-security-jwt</artifactId>
</dependency>
<dependency>
  <groupId>io.micronaut.security</groupId>
  <artifactId>micronaut-security-annotations</artifactId>
  <scope>provided</scope>
</dependency>

The processor must also appear in the compiler plugin's annotationProcessorPaths, or @Secured is silently ignored and every route is open. That is the first thing to check when a protected endpoint answers 200 without a token.

src/main/resources/application.ymlYAML
micronaut:
  security:
    authentication: bearer
    token:
      jwt:
        signatures:
          secret:
            generator:
              secret: '"${JWT_SIGNING_SECRET}"'
              jws-algorithm: HS256
        generator:
          access-token:
            expiration: 900

authentication: bearer turns on the login endpoint and tells Micronaut to read Authorization: Bearer headers. The secret comes from an environment variable. The nested quotes are intentional: Micronaut treats the value as a string and the inner quotes stop YAML from mangling a secret that contains special characters. For HS256 the key must be at least 256 bits, which is 32 random bytes. Generate it with openssl rand -base64 48 and keep it in your secret store, not in the repository. If the variable is missing, the application fails at startup, which is the behaviour you want.

Checking the credentials

Micronaut does not know where your users live. You tell it by providing a bean that turns a username and password into an authentication result.

src/main/java/dev/javahacks/security/UserAuthenticationProvider.javajava
@Singleton
class UserAuthenticationProvider<B> implements HttpRequestAuthenticationProvider<B> {

    private final UserRepository users;
    private final PasswordHasher hasher;

    UserAuthenticationProvider(UserRepository users, PasswordHasher hasher) {
        this.users = users;
        this.hasher = hasher;
    }

    @Override
    public AuthenticationResponse authenticate(
            @Nullable HttpRequest<B> request,
            AuthenticationRequest<String, String> credentials) {
        return users.findByUsername(credentials.getIdentity())
            .filter(u -> hasher.matches(credentials.getSecret(), u.passwordHash()))
            .<AuthenticationResponse>map(u -> AuthenticationResponse.success(u.username(), u.roles()))
            .orElseGet(AuthenticationResponse::failure);
    }
}

Three details are easy to get wrong. The password is compared against a hash with a purpose-built algorithm, as in hashing passwords with Argon2 or bcrypt, never with equals on plaintext. A missing user and a wrong password return the same failure(), so the response does not reveal which usernames exist. And the roles you pass to success become the roles claim in the token, so what you put there is what @Secured can check later. The repository call blocks, so the provider runs on Micronaut's blocking executor; a reactive driver needs the reactive variant of this interface.

Protecting routes

src/main/java/dev/javahacks/orders/OrderController.javajava
@Controller("/orders")
@Secured(SecurityRule.IS_AUTHENTICATED)
class OrderController {

    @Get("/{id}")
    Order get(Long id, Authentication auth) {
        return orders.findForUser(id, auth.getName());
    }

    @Delete("/{id}")
    @Secured("ROLE_ADMIN")
    HttpResponse<?> delete(Long id) {
        orders.delete(id);
        return HttpResponse.noContent();
    }
}

IS_AUTHENTICATED accepts any valid token. A role string restricts a method further, and a method-level annotation overrides the class-level one. Notice that get passes the caller's name into the query. Checking that a token is valid is not the same as checking that the caller may see this order, and the second check belongs in the service layer. A valid token for user A must not read user B's order, which is the top item in the OWASP API list.

Logging in and calling a route

Shell
curl -s -X POST localhost:8080/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"alice","password":"correct horse"}'

The response contains access_token, token_type and expires_in, plus the username and roles. Use the token on the next call:

Shell
curl -s localhost:8080/orders/7 -H "Authorization: Bearer $TOKEN"

A missing or invalid token returns 401. A valid token without the required role returns 403. If you get 401 on a route you believe is public, the default rule is deny, so open it explicitly with @Secured(SecurityRule.IS_ANONYMOUS). Public routes such as health checks and the login endpoint need that annotation or an intercept URL rule.

Token lifetime

A JWT is valid until it expires, and the server holds no record of it, so it cannot be revoked by deleting a session. That drives the design. Keep access tokens short, 5 to 15 minutes, and issue a refresh token for a longer session. The line expiration: 900 above is 15 minutes. Micronaut can issue refresh tokens when you add a RefreshTokenPersistence bean, which stores them so that you can revoke one on logout or password change. Without persistence there is nothing to revoke, and a stolen token works until it expires.

Where the client keeps the token matters as much as how long it lives. A single-page app that stores it in localStorage exposes it to any script injected into the page. A cookie with HttpOnly and SameSite set keeps it out of reach of scripts, at the cost of needing CSRF protection. Pick deliberately, and read the Java security basics before building your own flow.

Reading claims and rotating the secret

The Authentication object injected into a controller exposes the claims through getAttributes(). The subject is getName(), and the roles are under the key set by micronaut.security.token.roles-name, which defaults to roles. If you need extra claims, such as a tenant id, implement JwtClaimsSetAdapter or override the claim generator, and keep the token small: it travels on every request, and proxies commonly reject headers above 8 KB.

Rotating a shared HMAC secret means every service that validates tokens must be updated at once, because they all hold the same key. If more than one service validates tokens, prefer an asymmetric signature (RS256 or ES256), where only the issuer holds the private key and the others fetch the public key from a JWKS endpoint. Micronaut supports both through micronaut.security.token.jwt.signatures.jwks. A symmetric secret is fine for one application that issues and validates its own tokens, and it is the wrong choice the day a second service needs to trust it.

Keep an eye on the clock too. Expiry checks use the validating server's time, so a skew of a few minutes between hosts makes fresh tokens look expired. Run NTP on every node, and do not widen the expiry to hide a clock problem.

Testing

java
@MicronautTest
class OrderControllerTest {

    @Inject @Client("/") HttpClient client;

    @Test
    void rejects_a_request_without_a_token() {
        var ex = assertThrows(HttpClientResponseException.class,
            () -> client.toBlocking().exchange(HttpRequest.GET("/orders/7")));
        assertEquals(HttpStatus.UNAUTHORIZED, ex.getStatus());
    }
}

This test is the guard against the missing annotation processor problem described above. Test setup is covered in testing Micronaut apps.

Rotating keys without downtime

With a symmetric secret, rotation means every instance changes at once, which cannot happen in a rolling deploy. Accept two keys during the changeover: validate against the new key first, then the old one, and issue tokens with the new one. Remove the old key after the longest token lifetime has passed. With asymmetric signing and a JWKS endpoint, the issuer publishes both public keys, tagged by kid, and validators pick the right one from the token header, so rotation needs no coordination.

When a bearer token is the wrong tool

If the application renders HTML for a browser and talks only to its own frontend, a server-side session with a cookie is simpler and revocable. JWTs fit APIs consumed by several clients and services. The same ideas in Spring are in the Spring MVC REST guide, and Micronaut's own project tutorial covers the setup this post assumes.

The token format is defined in RFC 7519, and every property above is documented in the Micronaut Security guide.

Also inSecurity
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.