0Pricing
Spring Security 6 & JWT Authentication · Leçon

Accéder à l’utilisateur OAuth2 authentifié

Apprenez à lire le profil et les attributs de l’utilisateur connecté depuis une connexion OAuth2 dans Spring Security, à l’aide de OAuth2User et OidcUser.

Accéder à l’utilisateur OAuth2 authentifié est une leçon Spring Security 6 & JWT Authentication gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Spring Security 6 & JWT Authentication, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Spring Security 6 & JWT Authentication comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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.

Questions Fréquemment Posées

La leçon « Accéder à l’utilisateur OAuth2 authentifié » est-elle gratuite ?

Oui — le texte complet de « Accéder à l’utilisateur OAuth2 authentifié » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Spring Security 6 & JWT Authentication, passe à CoddyKit PRO. Le cours Spring Security 6 & JWT Authentication comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Accéder à l’utilisateur OAuth2 authentifié » ?

Apprenez à lire le profil et les attributs de l’utilisateur connecté depuis une connexion OAuth2 dans Spring Security, à l’aide de OAuth2User et OidcUser. Tu pratiques Spring Security 6 & JWT Authentication avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Spring Security 6 & JWT Authentication ?

Aucune expérience préalable n'est requise. Spring Security 6 & JWT Authentication sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Accéder à l’utilisateur OAuth2 authentifié » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Spring Security 6 & JWT Authentication ?

Oui. Chaque leçon Spring Security 6 & JWT Authentication inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Configuration d’un client OAuth2
  2. Intégration de la connexion via les réseaux sociaux
  3. Gestionnaire personnalisé de réussite OAuth2
  4. Accéder à l’utilisateur OAuth2 authentifié
← Retour à Spring Security 6 & JWT Authentication