在 cookie 中存储 JWT 令牌后,如何在 ASP.NET Core 3.1 中破坏该 cookie 并获取信息

Posted

技术标签:

【中文标题】在 cookie 中存储 JWT 令牌后,如何在 ASP.NET Core 3.1 中破坏该 cookie 并获取信息【英文标题】:After store JWT token in cookie how to break that cookie and get information in ASP.NET Core 3.1 【发布时间】:2021-02-20 11:28:32 【问题描述】:

在我的 ASP.NET Core 3.1 MVC 应用程序中,我想将 JWT 令牌存储在 cookie 中,然后在授权期间我想中断获取用户信息。这是我如何将 JWT 令牌存储在 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);

【问题讨论】:

【参考方案1】:

您可以使用此代码:

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

然后访问值:

principal.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Name)?.Value; 

【讨论】:

以上是关于在 cookie 中存储 JWT 令牌后,如何在 ASP.NET Core 3.1 中破坏该 cookie 并获取信息的主要内容,如果未能解决你的问题,请参考以下文章

将 JWT 令牌存储在 cookie 中

我们如何将 JWT 令牌存储在仅限 Http 的 cookie 中?

在哪里存储访问令牌以及如何跟踪用户(在 Http only cookie 中使用 JWT 令牌)

如何存储 JWT refreshToken cookie 响应

如何使用 Cookie 进行存储 jwt 令牌用户认证?

如何使用 DRF djangorestframework-simplejwt 包将 JWT 令牌存储在 HttpOnly cookie 中?