身份3 - 在数据库中存储声明但不存储cookie

时间:2017-03-05 02:33:14

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

In.net core Identity 3 - 默认情况下是否可以在Identity cookie中存储用户声明或角色声明,但仅将它们存储在数据库中?

换句话说,如果您想要访问声明,则必须明确加载它们。

无法使用Identity的内置功能和默认架构弄清楚如何配置它。

2 个答案:

答案 0 :(得分:1)

我仍然能够使用内置的AspNetRoleClaims表,但不会通过覆盖UserClaimsPrincipalFactory类将其包含在cookie中。再一次,原因是我有很多角色声称,而且cookie变得太大了。

我创建了自己的类AppClaimsPrincipalFactory,它继承自UserClaimsPrincipalFactory并覆盖CreateAsync方法:

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AppClaimsPrincipalFactory(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
    {
    }
    public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        if (user == null)
        {
            throw new ArgumentNullException(nameof(user));
        }
        var userId = await UserManager.GetUserIdAsync(user);
        var userName = await UserManager.GetUserNameAsync(user);
        var id = new ClaimsIdentity(Options.Cookies.ApplicationCookieAuthenticationScheme,
            Options.ClaimsIdentity.UserNameClaimType,
            Options.ClaimsIdentity.RoleClaimType);
        id.AddClaim(new Claim(Options.ClaimsIdentity.UserIdClaimType, userId));
        id.AddClaim(new Claim(Options.ClaimsIdentity.UserNameClaimType, userName));
        if (UserManager.SupportsUserSecurityStamp)
        {
            id.AddClaim(new Claim(Options.ClaimsIdentity.SecurityStampClaimType,
                await UserManager.GetSecurityStampAsync(user)));
        }

        // code removed that adds the role claims 

        if (UserManager.SupportsUserClaim)
        {
            id.AddClaims(await UserManager.GetClaimsAsync(user));
        }
        return new ClaimsPrincipal(id);
    }
}

在Startup.cs ConfigureServices中,我然后将其注册到容器中,如下所示:

services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

        // override UserClaimsPrincipalFactory (to remove role claims from cookie )
        services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();

答案 1 :(得分:0)

另一个选择是不在UserStore实现上实现IUserClaimStore接口。作为EF包的一部分的默认实现确实实现了此接口,因此自动存储和检索声明。

相关问题