IdentityServer4 - 从 IProfileService 实现中调用 API

IdentityServer4 - Calling API from IProfileService implementation

我正在开发一个 MVC 网络项目,该项目使用 IdentityServer4 对用户进行身份验证,然后该网络应用程序使用 IdentityServer(授权代码流)提供给用户的访问令牌来调用 API。 IdentityServer 已配置为使用 Azure AD 作为外部身份提供者,这是用户登录的主要机制。这一切都很好。

通过身份验证后,我需要查询网络应用程序的数据库以确定:

IdentityServer 文档 (http://docs.identityserver.io/en/latest/reference/profileservice.html) 建议为此实现 IProfileService 接口,我已经做到了。我希望 ProfileService 调用 Web 应用程序的 API 来检索有关用户的信息,以避免强制 IdentityServer 需要知道 about/directly 访问数据库。但是,我的问题是调用 API 虽然需要访问令牌。

是否可以在 ProfileService 的 IsActiveAsync / GetProfileDataAsync 方法中检索当前用户的令牌?我找不到确定令牌是否在此时生成的可靠文档。关于 authentication/authorization,我也是个菜鸟,这是一个很大的话题!

我想到了使用 ProfileService 中的客户端凭据流来调用 API,只是为了填充该初始令牌。但是,我不知道这是否是一个绝对糟糕的想法......或者是否有人可以向我推荐我可以调查的更好的概念。

谁能指出我正确的方向?

查看 ITokenCreationService,它是 identityserver4 的一部分。您可以将该服务注入到您的 IProfileService 实现中,然后使用您喜欢的任何声明创建一个新的不记名令牌。

例如:

protected readonly ITokenCreationService _tokenCreationService;

...

var token = new Token
{
    AccessTokenType = AccessTokenType.Jwt,
    Issuer = "https://my.identityserver.com",
    Lifetime = (int)TimeSpan.FromMinutes(5).TotalSeconds,
    Claims = GetClaimsNeededForApiCall()
};

string myToken = await _tokenCreationService.CreateTokenAsync(token);

...

无法在 ProfileService 中检索用户的 access_token。 只要 IdentityServer 需要 return 声明用户,就会调用配置文件服务。这意味着如果您尝试在 ProfileService 中为用户生成令牌,它将再次调用 ProfileService。