Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store data in cookie with asp.net core identity

I'm using ASP.NET core identity with EF end I would like to store data related to the user in the authentication cookie.

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);
}

but now I'm using ASP.NET Identity with EF and I can't find a way to store some data in the cookie.

like image 294
EricImhauser Avatar asked Sep 18 '16 08:09

EricImhauser


People also ask

Does ASP.NET Core identity use cookies?

ASP.NET Core Identity is a complete, full-featured authentication provider for creating and maintaining logins. However, a cookie-based authentication provider without ASP.NET Core Identity can be used. For more information, see Introduction to Identity on ASP.NET Core.

How do I use cookie authentication in .NET Core?

There are 3 steps for using cookie authentication. First is to add authentication middleware with the AddAuthentication and AddCookie methods. Secondly, specify the app must use authentication & authorization. Finally apply the [Authorize] attribute on the controllers and actions that require the cookie authorization.

What is ASP.NET Core identity?

ASP.NET Core Identity: Is an API that supports user interface (UI) login functionality. Manages users, passwords, profile data, roles, claims, tokens, email confirmation, and more.

What is ASP.NET Core session cookie?

Session uses a cookie to track and identify requests from a single browser. By default, this cookie is named . AspNetCore. Session , and it uses a path of / . Because the cookie default doesn't specify a domain, it isn't made available to the client-side script on the page (because HttpOnly defaults to true ).


1 Answers

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 });
    }
 }
like image 83
agua from mars Avatar answered Sep 22 '22 22:09

agua from mars