使用Jwt承载认证的自定义声明

时间:2016-09-27 08:05:48

标签: asp.net-core asp.net-identity claims-based-identity

我有一个使用JwtBearerAuthentication的应用程序。我想在每个请求开始时将我的应用程序声明添加到User(ClaimsPrincipal)。我设法使用ClaimsTransformationOptions

来做到这一点
app.UseClaimsTransformation(new ClaimsTransformationOptions
{
    Transformer = new ClaimsTransformer<TUser, TRole>()
});

和我的TransformAsync

public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext context)
{
    var services = context.Context.RequestServices;
    var userManager = services.GetRequiredService<UserManager<TUser>>();
    var roleManager = services.GetRequiredService<RoleManager<TRole>>();

    var userId = 1; // Get the UserId from my store, let say its 1 for now

    if (userId != 0)
    {
        var user = await userManager.FindByIdAsync(userId);

        var claimsPrincipal = await new UserClaimsPrincipalFactory<TUser, TRole>(userManager, roleManager, _optionsAccessor)
                .CreateAsync(user);

        context.Principal.AddIdentities(claimsPrincipal.Identities);
    }

    return context.Principal;
}

到目前为止一直很好,声明正从数据库加载并添加到context.Principal。我的问题是,一旦我到达控制器,身份被覆盖!!

1 个答案:

答案 0 :(得分:2)

所以我通过app.UseClaimsTransformation app.UseJwtBearerAuthentication解决了这个问题,确保每当JWT修改ClaimsPrincipal ClaimsTransformation selModel: { selType: 'checkboxmodel', //mode: 'SINGLE', headerWidth: 62, //checkOnly: false, checkOnly: true,//this will check only when you click on checkbox allowDeselect: false, ignoreRightMouseSelection: true, listeners: { 'selectionchange': Ext.bind(function (view, records) { },this) } }, 之后打电话来补充我自己的主张。