访问已验证身份的 OAuth2 用户
学习如何在 Spring Security 中通过 OAuth2 登录读取已登录用户的个人资料和属性,使用 OAuth2User 和 OidcUser
访问已验证身份的 OAuth2 用户 是 CoddyKit 上的免费 Spring Security 6 & JWT Authentication 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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.
常见问题解答
「访问已验证身份的 OAuth2 用户」课时是免费的吗?
是的 — 「访问已验证身份的 OAuth2 用户」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Security 6 & JWT Authentication 课程的其余内容,请升级到 CoddyKit PRO。 Spring Security 6 & JWT Authentication 课程共包含 4 节课。
「访问已验证身份的 OAuth2 用户」这节课中我会学到什么?
学习如何在 Spring Security 中通过 OAuth2 登录读取已登录用户的个人资料和属性,使用 OAuth2User 和 OidcUser 你通过在浏览器中直接运行的动手代码来练习 Spring Security 6 & JWT Authentication,全天候 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 用户