Доступ к аутентифицированному пользователю OAuth2
Узнайте, как получать профиль и атрибуты вошедшего пользователя из сеанса OAuth2 в Spring Security с помощью OAuth2User и OidcUser
«Доступ к аутентифицированному пользователю OAuth2» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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
OAuth2UserorOidcUserwith@AuthenticationPrincipal - Read attributes with
getAttributeor typed OIDC accessors - Map provider data to a local account on first login
- Customize with a
DefaultOAuth2UserServicesubclass
This connects external identity to your application's own user model.
Изучай Java с ИИ-репетитором — бесплатно
Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.
- Курсы
- 12
- Уроки
- 48
Часто задаваемые вопросы
Урок «Доступ к аутентифицированному пользователю OAuth2» бесплатный?
Да — полный текст урока «Доступ к аутентифицированному пользователю OAuth2» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.
Чему я научусь в уроке «Доступ к аутентифицированному пользователю OAuth2»?
Узнайте, как получать профиль и атрибуты вошедшего пользователя из сеанса OAuth2 в Spring Security с помощью OAuth2User и OidcUser Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?
Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Доступ к аутентифицированному пользователю OAuth2»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?
Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Настройка клиента OAuth2
- Интеграция входа через социальные сети
- Пользовательский обработчик успешной аутентификации OAuth2
- Доступ к аутентифицированному пользователю OAuth2