如何将 Jwt 令牌存储在 Cockie Storage 中并允许 [Auhorize] 仅检查该 cookie

问题描述

希望你们一切都好。我在 asp.net core 2.1 中遇到了会话超时问题,但没有找到任何解决方案。现在我正在尝试使用 Jwt 进行身份验证,我看到人们仅将 Jwt 用于 Api,但我也想将它用于我的网站请求。问题是如何将生成的令牌存储在 cookie 存储中并允许 [Authorize] 属性仅检查该 coockie 或令牌。我很困惑,卡住了。

解决方法

针对这种情况,您可以添加一个事件OnMessageReceived来接收来自cookie的token。

services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
        .AddCookie(config=>
        {
            config.Cookie.Name = "authname";
        })
.AddJwtBearer(o =>
{
   o.Events = new JwtBearerEvents()
  {

     //get cookie value
     OnMessageReceived = context =>
     {
       var a = "";
       context.Request.Cookies.TryGetValue("authname",out a);
       context.Token = a;
       return Task.CompletedTask;
     }
 };
 o.TokenValidationParameters = new TokenValidationParameters
 {
   NameClaimType = JwtClaimTypes.Name,RoleClaimType = JwtClaimTypes.Role,ValidIssuer = "http://localhost:5200",ValidAudience = "api",IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("---this is a long key---"))
   //...
 };
});

在控制器中,生成令牌时,将令牌附加到此 cookie。

public IActionResult Authenticate()
{
    //...
    var token = tokenHandler.CreateToken(tokenDescriptor);
    var tokenString = tokenHandler.WriteToken(token);
    
    Response.Cookies.Append("authname",tokenString);
    return View();
}

在每个请求中,它都会携带这个cookie。该事件将从请求中提取其值,[Authorize] 属性将检查令牌是否有效。