Spring Security 6 & JWT Authentication · Lección

Acceso al usuario autenticado de OAuth2

Aprenda a leer el perfil y los atributos del usuario que ha iniciado sesión mediante OAuth2 en Spring Security usando OAuth2User y OidcUser.

Lección 4 de 413 pasos

Acceso al usuario autenticado de OAuth2 es una lección gratuita de Spring Security 6 & JWT Authentication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Security 6 & JWT Authentication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Gratis para empezar

Aprende Java con un tutor de IA — gratis

Escribe y ejecuta código real en tu navegador, obtén ayuda instantánea de un tutor de IA disponible 24/7 y continúa donde lo dejaste en la web o en la aplicación.

Cursos
12
Lecciones
48

Preguntas frecuentes

¿La lección «Acceso al usuario autenticado de OAuth2» es gratis?

Sí — el texto completo de «Acceso al usuario autenticado de OAuth2» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Security 6 & JWT Authentication, actualiza a CoddyKit PRO. El curso de Spring Security 6 & JWT Authentication incluye 4 lecciones en total.

¿Qué aprenderé en «Acceso al usuario autenticado de OAuth2»?

Aprenda a leer el perfil y los atributos del usuario que ha iniciado sesión mediante OAuth2 en Spring Security usando OAuth2User y OidcUser. Practicas Spring Security 6 & JWT Authentication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Spring Security 6 & JWT Authentication?

No se requiere experiencia previa. Spring Security 6 & JWT Authentication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Acceso al usuario autenticado de OAuth2»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Spring Security 6 & JWT Authentication?

Sí. Cada lección de Spring Security 6 & JWT Authentication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Configuración de un cliente OAuth2
  2. Integración del inicio de sesión social
  3. Manejador personalizado de éxito OAuth2
  4. Acceso al usuario autenticado de OAuth2
← Volver a Spring Security 6 & JWT Authentication