0Pricing
Spring Security 6 & JWT Authentication · Lezione

Accedere all'utente OAuth2 autenticato

Impari a leggere il profilo e gli attributi dell'utente autenticato tramite un accesso OAuth2 in Spring Security, usando OAuth2User e OidcUser.

Accedere all'utente OAuth2 autenticato è una lezione Spring Security 6 & JWT Authentication gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Security 6 & JWT Authentication, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

After Login, Then What?

Once a user signs in through an OAuth2 provider, your app needs their profile: name, email, and provider id. Spring Security exposes this through a principal object you can inject anywhere.

The OAuth2User Principal

For plain OAuth2 logins, the authenticated principal is an OAuth2User. It holds the provider's attributes as a map plus the granted authorities.

public interface OAuth2User {
    Map<String, Object> getAttributes();
    Collection<? extends GrantedAuthority> getAuthorities();
    String getName();
}

Injecting the Principal

Use the @AuthenticationPrincipal annotation on a controller parameter to receive the current user directly.

@GetMapping('/me')
public Map<String,Object> me(@AuthenticationPrincipal OAuth2User user) {
    return user.getAttributes();
}

Reading Specific Attributes

Pull individual fields with getAttribute. The available keys depend on the provider, for example name and email from Google.

String email = user.getAttribute('email');
String name = user.getAttribute('name');

OIDC Logins and OidcUser

When the provider uses OpenID Connect, the principal is an OidcUser, a richer type that also exposes the ID token and standardized claims.

@GetMapping('/profile')
public String profile(@AuthenticationPrincipal OidcUser user) {
    return user.getFullName();
}

Standard OIDC Claims

OidcUser gives typed access to standard claims like getEmail(), getPicture(), and getPreferredUsername(), so you do not have to know each provider's raw keys.

String pic = user.getPicture();
String sub = user.getSubject();

Getting the User Elsewhere

Outside controllers, read the principal from the SecurityContext.

Authentication auth = SecurityContextHolder
    .getContext().getAuthentication();
OAuth2User user = (OAuth2User) auth.getPrincipal();

Mapping to a Local User

You usually want a local account record. On first login, look up the user by email or provider subject; if none exists, create one.

User local = repo.findByEmail(user.getAttribute('email'))
    .orElseGet(() -> repo.save(fromOAuth(user)));

Custom OAuth2UserService

To transform attributes or add roles at login time, extend DefaultOAuth2UserService and override loadUser. Return your own enriched principal.

public OAuth2User loadUser(OAuth2UserRequest req) {
    OAuth2User user = super.loadUser(req);
    return enrichWithRoles(user);
}

Provider Differs by registrationId

The same callback can serve multiple providers. Read the registrationId (google, github, etc.) from the request to know which provider's attribute schema to use.

String provider = req.getClientRegistration()
    .getRegistrationId();

Don't Trust Blindly

Treat provider attributes as input. Verify the email is marked verified when the provider supports it, and avoid using a mutable display name as a primary key.

Quick Check

Test your understanding of accessing the OAuth2 user.

Recap

You learned to read the authenticated OAuth2 user:

  • Inject OAuth2User or OidcUser with @AuthenticationPrincipal
  • Read attributes with getAttribute or typed OIDC accessors
  • Map provider data to a local account on first login
  • Customize with a DefaultOAuth2UserService subclass

This connects external identity to your application's own user model.

Domande Frequenti

La lezione «Accedere all'utente OAuth2 autenticato» è gratuita?

Sì — il testo completo di «Accedere all'utente OAuth2 autenticato» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Security 6 & JWT Authentication, passa a CoddyKit PRO. Il corso Spring Security 6 & JWT Authentication include 4 lezioni in totale.

Cosa imparerò in «Accedere all'utente OAuth2 autenticato»?

Impari a leggere il profilo e gli attributi dell'utente autenticato tramite un accesso OAuth2 in Spring Security, usando OAuth2User e OidcUser. Eserciti Spring Security 6 & JWT Authentication con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Security 6 & JWT Authentication?

Non è richiesta alcuna esperienza precedente. Spring Security 6 & JWT Authentication su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Accedere all'utente OAuth2 autenticato»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Security 6 & JWT Authentication?

Sì. Ogni lezione Spring Security 6 & JWT Authentication include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Configurazione del client OAuth2
  2. Integrazione dell'accesso tramite social
  3. Gestore personalizzato del successo OAuth2
  4. Accedere all'utente OAuth2 autenticato
← Torna a Spring Security 6 & JWT Authentication