【问题标题】:Get user profile in ASP.net core API with Identity Server 4 Implicit Flow使用 Identity Server 4 隐式流在 ASP.net 核心 API 中获取用户配置文件
【发布时间】:2020-05-26 08:19:20
【问题描述】:
我创建了一个使用 Identity Server 4 保护的 ASP.net 核心 API,它为通过隐式流获取 id 令牌和访问令牌的反应客户端提供服务。我能够成功验证从客户端到 API 的请求。
我的问题是我需要在 API 中访问请求用户的个人资料(或至少是他们的用户 ID)。目前,我只能访问不记名令牌中包含的用户声明。是否有某种方法可以设置我的 API,以便使用某种中间件从权威机构检索用户配置文件?我需要在请求中传递 ID 令牌吗?
感谢您的宝贵时间。
【问题讨论】:
标签:
asp.net-identity
identityserver3
identityserver4
asp.net-core-webapi
【解决方案1】:
您应该能够在安全原则声明中找到“Sub”。这是一个用户ID。然后您可以查询您的用户存储以获取用户信息。
理论上,您的 JWT 应该包含您的资源经常想要使用的声明(用户信息),这样您就可以最大限度地减少到数据库的往返行程。不建议在 JWT 声明中包含敏感信息。
你也可以查询用户信息
"userinfo_endpoint": "https://rmedev1.dca.com.au:8000/identity/server/connect/userinfo",
如果您使用的是 IdentityServer4.AccessTokenValidation 中间件,您应该可以使用自省服务来查询用户信息。
http://docs.identityserver.io/en/release/endpoints/userinfo.html
var userInfoClient = new UserInfoClient(doc.UserInfoEndpoint, token);
var response = await userInfoClient.GetAsync();
var claims = response.Claims;
【解决方案2】:
最后,解决方案非常简单。我在身份服务器中实现了 IdentityServer4.ServicesIProfileService,这使我可以向访问令牌添加任何和所有必需的声明。
然后在我的身份服务器启动中,我将我的配置文件服务注册为配置文件服务。
services.AddScoped<IProfileService, MyProfileService>();