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

前端之家收集整理的这篇文章主要介绍了使用asp.net核心身份将数据存储在cookie中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用带有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身份与EF,我找不到一种方法来存储cookie中的一些数据.

解决方法

使用UserManager的AddClaimsAsync或AddClaimAsync< YourUserIdentity>.例如,当您登录用户时,请执行以下操作:
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 });
    }
 }
原文链接:https://www.f2er.com/aspnet/251377.html

猜你在找的asp.Net相关文章