Asp.net web api 添加角色声明-我应该使用ICLAIMSSTransformer吗

Asp.net web api 添加角色声明-我应该使用ICLAIMSSTransformer吗,asp.net-web-api,asp.net-identity,.net-core,claims-based-identity,authorize-attribute,Asp.net Web Api,Asp.net Identity,.net Core,Claims Based Identity,Authorize Attribute,我们希望向当前主体添加大量角色声明(我们使用Authorize(Roles)属性),并发现iclaimsstransformer看起来非常适合 我们是这样登记的 app.UseClaimsFormation(新的ClaimsFormation选项 { Transformer=新的GetRolesFromDatabaseClaimsTransformer(新的RoleManager 2(Configuration.GetConnectionString(“ourcoolapp”)) }); 转

我们希望向当前主体添加大量角色声明(我们使用
Authorize(Roles)
属性),并发现
iclaimsstransformer
看起来非常适合

我们是这样登记的

app.UseClaimsFormation(新的ClaimsFormation选项
{
Transformer=新的GetRolesFromDatabaseClaimsTransformer(新的RoleManager 2(Configuration.GetConnectionString(“ourcoolapp”))
});
转换如下:

public Task TransformAsync(claimtransformationcontext)
{
//一种不加载所有请求的黑客方法。更好的主意?
如果(!context.context.Request.Path.Value.Contains(“api/”))
{
返回Task.FromResult(context.Principal);
}
var roleClaims=rolemager.GetRolesForUser(context.Principal.Identity.Name);
var索赔=新列表{};
var identity=context.Principal.identity作为索赔实体;
claims.AddRange(identity.claims);
索赔。AddRange(roleClaims);
var userIdentity=新的索赔实体(索赔,“本地”);
var userPrinicpal=新的ClaimsPrincipal(userIdentity);
返回Task.FromResult(userPrinicpal);
}
问:是否有其他更明智的方式添加角色声明

谢谢


Larsi

另一种选择可能是

它提供了为给定用户创建索赔主体的方法,您可以像
ClaimsTransformer
一样对其进行自定义

默认情况下,它会将
UserName
UserId
添加到索赔集合中。 为了定制它,您可以从
UserClaimsPrincipalFactory
驱动程序并覆盖
CreateAsync

公共类AppClaimsPrincipalFactory:UserClaimsPrincipalFactory
{
公共AppClaimsPrincipalFactory(用户管理器用户管理器,
RoleManager RoleManager,
IOPS选项访问器,

ILogger.

@Larsi-和其他选项是定制UserStore并实现GetClaimsAsync,但在本例中,声称存储在cookie中,它拥有自己的优点和硬币,如果您感兴趣,我将在下一个答案中编写实际示例;)考虑到CalimStRANScript和UserClaimsPrincipalFactory之间的区别在于,在CalimStRANScript中,您可以更改请求(在每个请求中),但在其他情况下,您第一次自定义身份(Suffin Meor)。请求索赔并在索赔后保存在cookie中;)敬请告知:
claimtransformationcontext
不在ASP Core 2.0.0中,
claimtransformer
不再是中间件。若要使用索赔信息,请在服务集合中注册它。有关更多信息,请跟随。