How to Store Jwt Token in Cockie Storage and Allow [Auhorize] to check only that cookie

Viewed 175

I hope you all good. I was suffering from Session Timeout in asp.net core 2.1 not come to any point of solution. Now I am trying Authentication using Jwt I see people use Jwt only for Api but I want to use it for my website requests also. The Question is How can I store the generated token inside the cookie storage and Allow [Authorize] attribute to check only that coockie or token. I am confused and stuck.

1 Answers

According to this situation, you can add an event OnMessageReceived to receive token from cookie.

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---"))
   //...
 };
});

In the controller, when generating a token, append the token to this cookie.

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

In every request, it will carry this cookie. The event will extract its value from the request, and [Authorize] attribute will check whether the token is valid.

Related