Blazor Interactive Server集成Google OAuth2后如何获取用户身份信息
获取Blazor Interactive Server(Identity Library)中Google OAuth2用户信息的方法
在完成Google OAuth2认证配置后,用户身份信息会以**声明(Claims)**的形式存储在ClaimsPrincipal对象中,你可以通过以下方式获取所需信息:
1. 用户唯一标识GUID(永久不变,不受邮箱变更影响)
Google OAuth返回的sub声明是用户的永久唯一ID,Identity通常会将其映射到ClaimTypes.NameIdentifier,可以通过两种方式提取:
var permanentUserId = User.FindFirstValue(ClaimTypes.NameIdentifier) ?? User.FindFirstValue("sub");
2. 用户邮箱
通过ClaimTypes.Email声明获取,前提是你在OAuth配置中包含了email scope:
var userEmail = User.FindFirstValue(ClaimTypes.Email);
3. 用户手机号码
需额外申请https://www.googleapis.com/auth/userinfo.phone权限,并在OAuth配置中添加该scope。用户同意授权后,可通过以下方式获取:
var userPhone = User.FindFirstValue(ClaimTypes.MobilePhone) ?? User.FindFirstValue("phone_number");
注意:仅当用户Google账号绑定了手机号且同意授权时,才能获取到该信息。
4. 用户家庭地址
需额外申请https://www.googleapis.com/auth/userinfo.address权限,并添加对应scope。地址信息会拆分为多个细分声明,或返回完整结构化数据:
// 拆分获取地址组件 var street = User.FindFirstValue(ClaimTypes.StreetAddress); var city = User.FindFirstValue(ClaimTypes.Locality); var country = User.FindFirstValue(ClaimTypes.Country); // 或获取完整地址字符串 var fullAddress = User.FindFirstValue("address");
注意:地址信息需要用户明确授权,且返回格式可能因地区存在差异。
关键配置说明
在Program.cs中配置Google OAuth时,必须添加对应scope才能获取敏感信息:
builder.Services.AddAuthentication() .AddGoogle(options => { options.ClientId = "你的Google客户端ID"; options.ClientSecret = "你的Google客户端密钥"; // 按需添加所需scope options.Scope.Add("email"); options.Scope.Add("https://www.googleapis.com/auth/userinfo.phone"); options.Scope.Add("https://www.googleapis.com/auth/userinfo.address"); });
内容的提问来源于stack exchange,提问作者David Thielen
相关产品推荐
相关产品推荐

