認証済みOAuth2ユーザーへのアクセス
OAuth2UserとOidcUserを使い、Spring SecurityのOAuth2ログインからログイン中のユーザーのプロフィールや属性を読み取る方法を学びます。
「認証済みOAuth2ユーザーへのアクセス」はCoddyKit上の無料Spring Security 6 & JWT Authenticationレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これは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.
AI チューターと学ぶ Java — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「認証済みOAuth2ユーザーへのアクセス」レッスンは無料ですか?
はい。「認証済みOAuth2ユーザーへのアクセス」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Security 6 & JWT Authenticationコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Security 6 & JWT Authenticationコースには全4レッスンが含まれています。
「認証済みOAuth2ユーザーへのアクセス」で何を学びますか?
OAuth2UserとOidcUserを使い、Spring SecurityのOAuth2ログインからログイン中のユーザーのプロフィールや属性を読み取る方法を学びます。 ブラウザで直接実行するハンズオンコードでSpring Security 6 & JWT Authenticationを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Spring Security 6 & JWT Authenticationを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSpring Security 6 & JWT Authenticationは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「認証済みOAuth2ユーザーへのアクセス」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSpring Security 6 & JWT Authenticationレッスンでコードを書いて実行できますか?
はい。すべてのSpring Security 6 & JWT Authenticationレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- OAuth2クライアントのセットアップ
- ソーシャルログインの統合
- カスタムOAuth2成功ハンドラー
- 認証済みOAuth2ユーザーへのアクセス