【问题标题】:Store data in cookie with asp.net core identity使用 asp.net 核心身份将数据存储在 cookie 中
【发布时间】:2017-01-26 02:50:39
【问题描述】:

我在 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 中存储一些数据的方法。

【问题讨论】:

  • 不确定您所说的“带有 EF 的 ASP.NET 身份”是什么意思 - 您指的是 this 之类的东西吗?
  • 你得到它的工作伙伴了吗?

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


【解决方案1】:

在我阅读@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));
                }
            };
        });

【讨论】:

  • 我也不知道这些选项
  • 选项 2 看起来很有趣。它是否也将声明存储在数据库中?
  • 一直在寻找一种方法来保持从 http 调用到 http 调用的自定义声明,尝试了十几件事,但没有一个真正做到这一点。我试过这个,但在 .NET Core 3.1 中,IdentityOptions 没有 Cookies 属性。
【解决方案2】:

使用AddClaimsAsync 或AddClaimAsync 或UserManager&lt;YourUserIdentity&gt;。例如,当您登录用户时:

public class AccountController : Controller
{
    public UserManager<YourUserIdentity> UserManager { get; private set; }

    public SignInManager<YourUserIdentity> SignInManager { get; private set; }

    public AccountController(UserManager<YourUserIdentity> userManager, 
        SignInManager<YourUserIdentity> signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByNameAsync(model.UserName);

            await UserManager.AddClaimAsync(user, new Claim("your-claim", "your-value"));

            var signInStatus = await SignInManager.PasswordSignInAsync(user, model.Password, model.RememberMe, lockoutOnFailure: false);

            if (signInStatus.Succeeded)
                return RedirectToLocal(returnUrl);

            ModelState.AddModelError("", "Invalid username or password.");
            return View(model);
        }

        // If we got this far, something failed, redisplay form
        return View("Index", new LoginPageViewModel() { Login = model });
    }
 }

【讨论】:

  • 谢谢,但这会将表 aspuserclaims 中的数据保存在数据库中。它是否也将数据保存在身份验证 cookie 中?有没有办法只在 cookie 中而不在表中保存数据。我真的不想每次需要数据时都调用数据库,我想在没有会话的情况下工作
  • 是的,如果您使用 cookie 身份验证,这会将声明存储在身份验证 cookie 中
  • ConfigureServices方法中如何配置cookie认证?
  • 身份默认使用cookie认证
  • 好的,但我不想将数据保存在数据库中,而只想保存在 cookie 中。我怎样才能做到这一点?
猜你喜欢
  • 2021-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-11
  • 2017-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多