Rau*_*ros 4 asp.net-mvc claims-based-identity asp.net-identity asp.net-core identityserver4
对不起我的英语不好。
我有三个项目:IdentityServer,Ensino.Mvc,Ensino.Api。IdentityServer项目提供了IdentityServer4库中的主要身份信息和声明-声明配置文件,声明地址,声明Sid ...等。Ensino.Mvc项目以令牌形式获取此信息,并将其发送到API,以便MVC被授予对资源的访问权限。令牌包含IdentityServer提供的所有声明。但是在API中,我需要生成其他特定于API的声明,例如:声明EnrollmentId,它对应于令牌中的声明Sid。我也想在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();
Run Code Online (Sandbox Code Playgroud)
在没有API的其他Project中,只有mvc,我已经继承UserClaimsPrincipalFactory并重写CreateAsync以添加其他声明。我喜欢在API项目中做类似的事情。可能吗?
最好的方法是什么?
编辑:经过一些研究,我想做的是:通过IdentityServer进行身份验证,并根据声明和特定的api数据库数据在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"));
};
});
Run Code Online (Sandbox Code Playgroud)
请注意,这将在对API的每个请求上运行,因此,如果您要从数据库加载信息,则最好缓存声明。
此外,Identity Server仅应负责标识用户,而不是标识用户的身份。它们的作用是特定于应用程序的(角色,权限等),因此您可以正确识别并避免与Identity Server的逻辑交叉。
| 归档时间: |
|
| 查看次数: |
1286 次 |
| 最近记录: |