1

In my ASP.NET Core 3.1 MVC application I want to store JWT token in cookie then during Authorization I want to break that get user information. This is the code how I store JWT token in cookie.

var tokenHandler = new JwtSecurityTokenHandler();
var secrect = configuration.GetValue<string>("Secret");
var key = Encoding.ASCII.GetBytes(secrect);

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(new Claim[]
    {
         new Claim(ClaimTypes.Name, user.UserName),
         new Claim(ClaimTypes.NameIdentifier, user.UserId.ToString())
    }),
         Expires = DateTime.UtcNow.AddDays(1),
         SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
              SecurityAlgorithms.HmacSha256Signature)
 };

 var token = tokenHandler.CreateToken(tokenDescriptor);

 var cookieOptions = new CookieOptions
 {
      // Set the secure flag, which Chrome's changes will require for SameSite none.
      // Note this will also require you to be running on HTTPS.
      Secure = false,

      // Set the cookie to HTTP only which is good practice unless you really do need
      // to access it client side in scripts.
      HttpOnly = false,

      // Add the SameSite attribute, this will emit the attribute with a value of none.
      // To not emit the attribute at all set
      // SameSite = (SameSiteMode)(-1)
      // SameSite = SameSiteMode.Lax
 };

 //// Add the cookie to the response cookie collection
 Response.Cookies.Append("auth-cookie", token.ToString(), cookieOptions);
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

You can use this code:

var secrect = configuration.GetValue<string>("Secret");
var key = Encoding.ASCII.GetBytes(secrect);
SecurityToken validatedToken;
TokenValidationParameters validationParameters = new TokenValidationParameters();

validationParameters.ValidateLifetime = true;
validationParameters.IssuerSigningKey = new SymmetricSecurityKey(key);

ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(jwtToken, validationParameters, out validatedToken);

Then access the value:

principal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value; 
Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61