对不起我的英语不好。
我有三个项目:IdentityServer、Ensino.Mvc、Ensino.Api。 IdentityServer 项目提供来自 IdentityServer4 库的主要身份信息和声明 - 声明配置文件、声明地址、声明 Sid...等。 Ensino.Mvc 项目在令牌中获取此信息并将其发送到 API,以便 MVC 有权访问资源。该令牌包含 IdentityServer 提供的所有声明。但在 API 中,我需要生成特定于 API 的其他声明,例如:与令牌中的声明 Sid 相对应的声明 EnrollmentId。我还想在 HttpContext 中添加此声明以供将来使用。有人可以告诉我如何实现这一目标吗?
我在 Startup.ConfigureServices 中有这段代码:
// Add identity services
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5100";
options.RequireHttpsMetadata = false;
options.ApiName = "beehouse.scope.ensino-api";
});
// Add mvc services
services.AddMvc();
在其他项目中,没有API,只有mvc,我继承了UserClaimsPrincipalFactory
并被覆盖CreateAsync
添加额外的索赔。我喜欢在 API 项目中做类似的事情。是否可以?
做到这一点的最佳方法是什么?
编辑:经过一些研究,我想做的是:根据声明和特定的 api 数据库数据,通过 IdentityServer 进行身份验证并在 api 中设置授权。
在您的 API 项目中,您可以添加自己的事件处理程序options.JwtBearerEvents.OnTokenValidated
。这就是点ClaimsPrincipal
已设置,您可以向身份添加声明或向主体添加新身份。
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:5100";
options.RequireHttpsMetadata = false;
options.ApiName = "beehouse.scope.ensino-api";
options.JwtBearerEvents.OnTokenValidated = async (context) =>
{
var identity = context.Principal.Identity as ClaimsIdentity;
// load user specific data from database
...
// add claims to the identity
identity.AddClaim(new Claim("Type", "Value"));
};
});
请注意,这将在对 API 的每个请求上运行,因此如果您要从数据库加载信息,最好缓存声明。
另外,Identity Server 应该只负责识别用户,而不是他们做什么。它们所做的事情是特定于应用程序的(角色、权限等),因此您正确地认识到了这一点并避免了与 Identity Server 的逻辑交叉。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)