Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท OAuth2 Login and OIDC

OIDC Login and ID Tokens in Spring Security

Add Log in with Google or Keycloak using oauth2Login: client registration properties, the OIDC ID token, nonce, claim validation and a runnable validator in Java.

OAuth2 says what an app may do. OpenID Connect (OIDC) adds the missing piece for login: a standard way to learn who the user is. When the scope openid is requested, the provider returns an ID token (always a JWT) next to the access token. It contains claims about the sign-in event: who, when, for which client, and how.

Spring Security's oauth2Login() implements the whole thing: redirecting to the provider, handling the callback, exchanging the code, validating the ID token, loading user information and creating a session. This lesson shows the configuration (read-only real code, because Spring cannot run on this site) and builds a runnable stand-in for the ID token validation step.

Configuration with Spring Boot

Register the provider in application.yml. Well-known providers (Google, GitHub, Okta, Facebook) have built-in defaults, so you only give the client id and secret:

YAML
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            scope: openid, profile, email
          keycloak:
            client-id: shop-web
            client-secret: ${KEYCLOAK_SECRET}
            authorization-grant-type: authorization_code
            scope: openid, profile
        provider:
          keycloak:
            issuer-uri: https://sso.example.com/realms/shop

Setting issuer-uri makes Spring fetch /.well-known/openid-configuration and learn the authorization, token, user-info and JWK endpoints. The filter chain then needs only:

Java
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(a -> a
            .requestMatchers("/", "/error").permitAll()
            .anyRequest().authenticated())
        .oauth2Login(Customizer.withDefaults())
        .logout(l -> l.logoutSuccessUrl("/"));
    return http.build();
}

Spring generates a login page at /login listing every registered provider, starts the flow at /oauth2/authorization/{registrationId} and receives the callback at /login/oauth2/code/{registrationId}. Remember to register that exact callback URL at the provider.

In a controller, the logged-in user is available as an OidcUser:

Java
@GetMapping("/me")
String me(@AuthenticationPrincipal OidcUser user) {
    return user.getFullName() + " <" + user.getEmail() + ">";
}

What is inside an ID token

Claim Meaning What to check
iss The provider's issuer URL Equals the configured issuer
sub Stable unique user id at that provider Use this as the key, not the email
aud Client ids the token is for Contains your client id
exp, iat Expiry and issue time Not expired, issued recently
nonce Value your app sent in the request Equals the one stored in the session
email, name, picture Profile claims Treat as data, check email_verified

ID token checklist

Signature Provider's key from JWKS
iss and aud Right issuer, right client
exp Not expired
nonce Matches our request
1 / 2

Spring's OidcIdTokenValidator performs these checks automatically when it receives the token. The stand-in below shows the logic with a plain claims map: you can see exactly which failure produces which error.

Java ID token claim validation (stand-in)

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.

The real decoder also verifies the signature against the provider's published keys before any claim is looked at. In Spring, ClientRegistrations.fromIssuerLocation(...) plus JwtDecoderFactory<ClientRegistration> build that decoder for you.

OAuth2 user versus OIDC user

Plain OAuth2 (GitHub) OIDC (Google, Keycloak, Okta)
Identity source A GET /user call to the provider's API The ID token, plus optional user-info endpoint
Principal type DefaultOAuth2User DefaultOidcUser
Stable id attribute Configured with user-name-attribute (for GitHub id) sub
Authorities OAUTH2_USER and SCOPE_* OIDC_USER and SCOPE_*

For plain OAuth2 providers that are not built in, you set the endpoints yourself:

YAML
spring:
  security:
    oauth2:
      client:
        provider:
          myprovider:
            authorization-uri: https://p.example.com/oauth/authorize
            token-uri: https://p.example.com/oauth/token
            user-info-uri: https://p.example.com/api/me
            user-name-attribute: id

Logging out of the provider too

Ending your own session does not end the provider's. For OIDC providers that support RP-initiated logout, Spring provides OidcClientInitiatedLogoutSuccessHandler, which redirects to the provider's end_session_endpoint with an id_token_hint so the user is signed out of the single sign-on session as well.

Do not identify users by email alone. Emails can change and some providers allow unverified addresses. Store the pair (iss, sub) as the account key, and only trust email when email_verified is true.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does OpenID Connect add to OAuth2?

    OAuth2 is about authorization. OIDC adds identity: the ID token and the openid scope.
  2. 2. Which claim should be the primary key of a user in your database?

    sub is stable per provider. Emails can change or be unverified.
  3. 3. What is the nonce for?

    The client sends a random nonce and expects it back inside the ID token.
  4. 4. Which URL receives the authorization code in a Spring Boot app by default?

    That is the default redirect URI pattern; register it exactly with the provider.

Summary

  • oauth2Login() runs the whole authorization code flow and creates a session.
  • With the openid scope, the provider returns an ID token whose claims Spring validates (signature, iss, aud, exp, nonce).
  • Use issuer-uri for OIDC discovery; set endpoints manually for plain OAuth2 providers.
  • Identify users by (iss, sub), not by email.
  • Plan for single logout with the provider.

Next: Custom user mapping and authorities