将数据存储在具有asp.net核心身份的cookie中 [英] Store data in cookie with asp.net core identity
本文介绍了将数据存储在具有asp.net核心身份的cookie中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 ASP.NET
核心身份与EF结束我想存储与用户相关的数据在认证cookie。
I'm using ASP.NET
core identity with EF end I would like to store data related to the user in the authentication cookie.
这是我以前用过的 ASP.NET 4.6
( appcontext
是数据存储):
This is how I used to do with ASP.NET 4.6
(appcontext
is the data to store):
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中的一些数据。
but now I'm using ASP.NET Identity
with EF
and I can't find a way to store some data in the cookie.
推荐答案
使用 AddClaimsAsync
或 AddClaimAsync
UserManager< YourUserIdentity>
。例如,当您登录您的用户时:
Use AddClaimsAsync
or AddClaimAsync
of UserManager<YourUserIdentity>
. for exemple like this when you sign in your user:
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 });
}
}
这篇关于将数据存储在具有asp.net核心身份的cookie中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文