Search code examples
asp.net-coreasp.net-identity

Save a value in authentication cookie when calling SignInAsync


I have a Login Page with three fields Username, Password and a dropdown list. The User is supposed to a select a value from dropdown list before signing.

I need to store the selected value of dropdown list in the Authentication Cookie and Able to Retrieve it on further requests.

Using AspNetCore Identity 2.0.0 for authentication.


Solution

  • You can read up on how to do this on https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x

    //somehow authenticate your user. I don't care how you do this.
    var user = await AuthenticateUser(Input.Email, Input.Password);
    
    //create a list of claims - all you need based on your user information
    //this si also where you store the information based on your ddl value
    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, user.Email),
        new Claim("FullName", user.FullName),
        new Claim("DropdownValue", /*ADD DROPDOWN VALUE HERE*/)
    };
    
    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    var authProperties = new AuthenticationProperties();
    
    
    await HttpContext.SignInAsync(
          CookieAuthenticationDefaults.AuthenticationScheme, 
          new ClaimsPrincipal(claimsIdentity), 
          authProperties);
    

    Eh voila. Done.