Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 38 ยท Security

OAuth 2.0 and OpenID Connect

Add login with Google, Keycloak or Okta to Micronaut using OAuth 2.0 and OpenID Connect: authorization code flow, PKCE, resource server setup and runnable flow stand-ins.

Writing your own login form means storing passwords. Many applications would rather let a specialist do it: Google, GitHub, Keycloak, Okta or Microsoft Entra. OAuth 2.0 is the standard that lets your application obtain limited access on a user's behalf, and OpenID Connect (OIDC) adds a layer on top that tells your application who the user is.

The real Micronaut OAuth2 module is not available on this site, so its configuration is read-only. The TryIt examples simulate the authorization code flow and the PKCE check in plain Java, because understanding the sequence is the hardest part.

The roles

  • Resource owner: the user.
  • Client: your application.
  • Authorization server: the identity provider that authenticates the user and issues tokens.
  • Resource server: an API that accepts tokens (it can be your Micronaut service).

OAuth 2.0 does not say how to log in; it defines how to obtain tokens. OIDC adds a standard ID token (a JWT about the user) and a userinfo endpoint, so "login with X" works the same way everywhere.

The authorization code flow

This is the flow to use for web applications:

  1. The user clicks "Log in". Your app redirects the browser to the provider's authorization endpoint with client_id, redirect_uri, scope=openid profile email and a random state.
  2. The user signs in at the provider and agrees.
  3. The provider redirects back to your redirect_uri with a short-lived code and the same state.
  4. Your server checks state, then calls the token endpoint (server to server, with the client_secret) to exchange the code for tokens.
  5. Your app validates the ID token and creates the user's session or token.

The code passes through the browser, but the tokens do not: they are fetched by your server over a direct connection. That is the point of the extra step.

Authorization code flow

Redirect App sends the browser to the provider.
Sign in The user authenticates there.
1 / 2

Micronaut as an OAuth 2.0 client

Add micronaut-security-oauth2 and micronaut-security-jwt, and configure the provider under a name you choose:

YAML
micronaut:
  security:
    authentication: cookie
    oauth2:
      enabled: true
      clients:
        keycloak:
          client-id: "${OAUTH_CLIENT_ID}"
          client-secret: "${OAUTH_CLIENT_SECRET}"
          openid:
            issuer: https://auth.example.org/realms/demo
    endpoints:
      logout:
        get-allowed: true

Micronaut then exposes /oauth/login/keycloak (start the flow) and /oauth/callback/keycloak (receive the code). It discovers all other endpoints from the issuer's /.well-known/openid-configuration document, checks state and the ID token's signature, issuer, audience and expiry, and creates the Authentication.

To turn the provider's claims into your roles, implement OpenIdAuthenticationMapper (or OauthAuthenticationMapper for plain OAuth 2.0 providers such as GitHub, which has no ID token). The mapper decides which claims become roles, for example mapping a groups claim to ROLE_* names.

Java
@Singleton
@Named("keycloak")
class KeycloakMapper implements OpenIdAuthenticationMapper {
    @Override
    public AuthenticationResponse createAuthenticationResponse(
            String providerName, OpenIdTokenResponse tokenResponse,
            OpenIdClaims claims, State state) {
        List<String> roles = claims.get("groups") instanceof List<?> g
                ? g.stream().map(x -> "ROLE_" + x.toString().toUpperCase()).toList()
                : List.of("ROLE_USER");
        return AuthenticationResponse.success(claims.getSubject(), roles);
    }
}

Micronaut as a resource server

When an API only needs to accept tokens issued elsewhere, it is a resource server. There is no login redirect; the API just validates the bearer token on each request, using the provider's public keys:

YAML
micronaut:
  security:
    authentication: bearer
    token:
      jwt:
        signatures:
          jwks:
            keycloak:
              url: https://auth.example.org/realms/demo/protocol/openid-connect/certs

Your controllers still use @Secured. Clients (single-page apps, mobile apps, other services) obtain tokens from the provider, never from your API.

PKCE for public clients

A mobile or browser-only app cannot keep a client secret. PKCE (Proof Key for Code Exchange) protects the code with a one-time secret: the client creates a random code_verifier, sends its SHA-256 hash (code_challenge) in step 1, and proves it knows the verifier in step 4. A stolen code is useless without the verifier. Modern guidance is to use PKCE for every client, including server-side ones.

Try it: the flow end to end

This stand-in has a tiny authorization server and a client in one program. It shows the state check and that a code can be used only once.

Java Authorization code flow

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.

Try it: PKCE challenge

Java PKCE verifier and challenge

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.

Security notes

  • Register exact redirect URIs at the provider; never accept wildcards.
  • Keep client_secret out of source control, as in Configuration Files and Environments.
  • Validate the ID token's iss, aud, exp and nonce; Micronaut does it for you, but do not turn the checks off.
  • Do not use the implicit flow or the password grant for new applications; they are deprecated.
  • Request only the scopes you need.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does OpenID Connect add to OAuth 2.0?

    OAuth 2.0 covers delegated access; OIDC adds identity through the ID token and userinfo endpoint.
  2. 2. Why is the code exchanged for tokens by the server and not the browser?

    The browser only sees a short-lived code; the token request is a direct server-to-server call.
  3. 3. What is the purpose of the state parameter?

    The client generates a random state and rejects callbacks that do not return the same value.
  4. 4. What does PKCE protect?

    Without the original code_verifier, a stolen code cannot be exchanged for tokens.

Summary

  • OAuth 2.0 delegates access; OIDC adds identity with an ID token.
  • Use the authorization code flow with PKCE; the browser sees only the code.
  • Micronaut can act as an OAuth 2.0 client (login redirects, mappers for roles) or as a resource server validating bearer tokens through JWKS.
  • Check state, issuer, audience and expiry, and keep secrets in the environment.

Next: Service Discovery and Distributed Configuration