Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

asp.net core - How to Store Jwt Token in Cockie Storage and Allow [Auhorize] to check only that cookie

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.

question from:https://stackoverflow.com/questions/65898709/how-to-store-jwt-token-in-cockie-storage-and-allow-auhorize-to-check-only-that

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...