Spring Security 6 & JWT Authentication · Lekcja

Dostęp do uwierzytelnionego użytkownika OAuth2

Dowiedz się, jak odczytywać profil i atrybuty zalogowanego użytkownika z logowania OAuth2 w Spring Security za pomocą OAuth2User i OidcUser.

Lekcja 4 z 413 kroki

Dostęp do uwierzytelnionego użytkownika OAuth2 to bezpłatna lekcja Spring Security 6 & JWT Authentication na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Security 6 & JWT Authentication, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Java dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Dostęp do uwierzytelnionego użytkownika OAuth2” jest bezpłatna?

Tak — pełny tekst „Dostęp do uwierzytelnionego użytkownika OAuth2” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Security 6 & JWT Authentication, przejdź na CoddyKit PRO. Kurs Spring Security 6 & JWT Authentication zawiera 4 lekcji w sumie.

Co nauczysz się w „Dostęp do uwierzytelnionego użytkownika OAuth2”?

Dowiedz się, jak odczytywać profil i atrybuty zalogowanego użytkownika z logowania OAuth2 w Spring Security za pomocą OAuth2User i OidcUser. Ćwiczysz Spring Security 6 & JWT Authentication z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Spring Security 6 & JWT Authentication?

Nie wymagamy żadnego doświadczenia. Spring Security 6 & JWT Authentication w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Dostęp do uwierzytelnionego użytkownika OAuth2”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Spring Security 6 & JWT Authentication?

Tak. Każda lekcja Spring Security 6 & JWT Authentication zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Konfiguracja klienta OAuth2
  2. Integracja logowania społecznościowego
  3. Niestandardowy handler pomyślnego uwierzytelniania OAuth2
  4. Dostęp do uwierzytelnionego użytkownika OAuth2
← Powrót do Spring Security 6 & JWT Authentication