使用asp.net核心身份将数据存储在cookie中

时间:2016-09-18 08:53:09

标签: asp.net asp.net-mvc entity-framework asp.net-core asp.net-identity

我在EF端使用ASP.NET核心身份我想在认证cookie中存储与用户相关的数据。

这就是我以前使用ASP.NET 4.6的方式(appcontext是要存储的数据):

public static void IdentitySignin(AppContext appContext, string providerKey = null, bool isPersistent = false)
{
    var claims = new List<Claim>();

    // create *required* claims
    claims.Add(new Claim(ClaimTypes.NameIdentifier, appContext.UserId.ToString()));
    claims.Add(new Claim(ClaimTypes.Name, appContext.UserName));

    // serialized AppUserState object
    claims.Add(new Claim("appcontext" + EZA.Store.AppContext.Version, appContext.ToString()));

    var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

    // add to user here!
    AuthenticationManager.SignIn(new AuthenticationProperties()
    {
        AllowRefresh = true,
        IsPersistent = isPersistent,
        ExpiresUtc = DateTime.UtcNow.AddDays(7),
    }, identity);
}

但现在我正在ASP.NET Identity使用EF,我无法找到在Cookie中存储某些数据的方法。

2 个答案:

答案 0 :(得分:7)

使用AddClaimsAsync的{​​{1}}或AddClaimAsync。例如,当您登录用户时,请执行以下操作:

UserManager<YourUserIdentity>

答案 1 :(得分:6)

在我阅读@ aqua的答案之前(我刚刚学会了这种方式),我会说你有两种选择:

1 - 覆盖UserClaimsPrincipalFactory,如下所示:

public class AppClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>
{
    public AppClaimsPrincipalFactory(
        UserManager<ApplicationUser> userManager,
        RoleManager<IdentityRole> roleManager,
        IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor)
    {
    }

    public async override Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
    {
        var principal = await base.CreateAsync(user);

        ((ClaimsIdentity)principal.Identity).AddClaims(new[] {
             new Claim("<claim name>", value)
        });

        return principal;
    }
}

// register it
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();

2-使用OnSigningIn事件。

        services.Configure<IdentityOptions>(opt =>
        {
            opt.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
            {
                OnSigningIn = async (context) =>
                {
                    ClaimsIdentity identity = (ClaimsIdentity)context.Principal.Identity;
                    identity.AddClaim(new Claim("<claim name>", value));
                }
            };
        });