Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท OAuth2 Login and OIDC

Custom User Mapping and Authorities for OAuth2 Login

Map OAuth2 and OIDC logins to your own users: OAuth2UserService, OidcUserService, GrantedAuthoritiesMapper, auto-provisioning and role claims, with runnable stand-ins.

After oauth2Login() succeeds you hold a principal full of provider data: GitHub gives login and id, Google gives sub, email and name. Your application usually needs more: a row in your own users table, application roles, maybe a tenant. This lesson shows the three extension points Spring Security offers and builds runnable stand-ins for the mapping logic.

The real Spring interfaces are read-only on this site; the stand-ins use plain Java records and maps, but the decisions are the same ones you write in the framework.

The three hooks

Hook Runs for Typical use
OAuth2UserService<OAuth2UserRequest, OAuth2User> Plain OAuth2 providers (GitHub) Load/create your user, add roles
OidcUserService OIDC providers (Google, Keycloak) Same, using ID token claims
GrantedAuthoritiesMapper Both Translate provider claims or groups into authorities
Java
@Bean
OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService(UserAccountService accounts) {
    OidcUserService delegate = new OidcUserService();
    return request -> {
        OidcUser oidc = delegate.loadUser(request);                  // standard behaviour
        UserAccount account = accounts.findOrCreate(
            request.getClientRegistration().getRegistrationId(),
            oidc.getSubject(), oidc.getEmail(), oidc.getFullName());
        Set<GrantedAuthority> authorities = new HashSet<>(oidc.getAuthorities());
        account.roles().forEach(r -> authorities.add(new SimpleGrantedAuthority("ROLE_" + r)));
        return new DefaultOidcUser(authorities, oidc.getIdToken(), oidc.getUserInfo());
    };
}

Spring Boot detects beans of these types and plugs them into oauth2Login() automatically. For plain OAuth2 providers, implement OAuth2UserService<OAuth2UserRequest, OAuth2User> and wrap DefaultOAuth2UserService the same way.

Provisioning an account on first login

The central rule: key accounts by (provider, subject) and never by email. First login creates the account, later logins find it. The stand-in uses an in-memory map for the database.

Java Find or create a local account (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.

Notice two safety rules in the code: the same person logging in through two providers creates two accounts (linking them needs an explicit, authenticated step, never an automatic match on email), and the staff role depends on email_verified, not just on the address text.

Account takeover through email matching. If you merge accounts automatically because the email is the same, an attacker who registers a victim's address at a provider that does not verify it can log in as the victim. Link accounts only after the user proves control of both.

Mapping provider roles and groups

Identity providers like Keycloak and Okta put groups or roles in claims. Keycloak, for example, nests realm roles in realm_access.roles. A GrantedAuthoritiesMapper can translate them:

Java
@Bean
GrantedAuthoritiesMapper authoritiesMapper() {
    return authorities -> {
        Set<GrantedAuthority> mapped = new HashSet<>();
        for (GrantedAuthority a : authorities) {
            if (a instanceof OidcUserAuthority oidc) {
                Map<String, Object> realm = oidc.getAttributes().get("realm_access") instanceof Map<?, ?> m
                    ? (Map<String, Object>) m : Map.of();
                Object roles = realm.get("roles");
                if (roles instanceof Collection<?> list) {
                    list.forEach(r -> mapped.add(new SimpleGrantedAuthority("ROLE_" + r.toString().toUpperCase())));
                }
            }
            mapped.add(a);
        }
        return mapped;
    };
}

Because the nesting is easy to get wrong, test the extraction logic separately. The stand-in does that with maps:

Java Extract nested role claims (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.

Missing or oddly shaped claims return an empty list instead of throwing: a login must not crash because a provider omitted an optional claim.

Customizing the success and failure pages

After login the user returns to the page they originally asked for. You can change this:

Java
.oauth2Login(login -> login
    .loginPage("/signin")                       // your own page with provider buttons
    .defaultSuccessUrl("/dashboard", false)     // false = prefer the saved request
    .failureUrl("/signin?error"))

Link to /oauth2/authorization/google from your custom page to start a provider flow.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should identify an external user account in your database?

    The pair (provider, sub) is stable and unique. Emails change and may be unverified.
  2. 2. Which hook turns a provider's groups claim into Spring authorities?

    GrantedAuthoritiesMapper receives the authorities Spring built and returns the final set.
  3. 3. Why is automatic account linking by email dangerous?

    Linking needs proof that the same person controls both accounts.
  4. 4. A provider omits the roles claim. What should your mapper do?

    Missing optional claims mean no extra roles. Failing closed on privileges, not on the login itself.

Summary

  • Use OidcUserService or OAuth2UserService wrappers to load or create your local account.
  • Key accounts by (provider, sub); verify email before trusting it.
  • GrantedAuthoritiesMapper converts provider roles and groups into authorities, and must tolerate missing claims.
  • Never link accounts automatically on email alone.
  • Customize login and success pages with oauth2Login options.

Next: CSRF protection