微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

在我的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);

解决方法

您可以使用以下代码:

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; 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。