ASP .Net Core, Store JWT in Cookie
Asked Answered
D

1

5

I heard its one of the most safety way to store JWT. My question is. How can I save it in cookie?

Here is the function in ConfigureServises in Startup.cs

services.AddControllers();
        services.AddTransient<IUserRepository, UserRepository>();
        services.AddTransient<ITokenService, TokenService>();
        IdentityModelEventSource.ShowPII = true;
          services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuer = true,
                  ValidateAudience = true,
                  ValidateLifetime = true,
                  ValidateIssuerSigningKey = true,
                  ValidIssuer = Configuration["Jwt:Issuer"],
                  ValidAudience = Configuration["Jwt:Issuer"],
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
              };
          });
Distasteful answered 29/6, 2022 at 7:43 Comment(0)
U
8

Options object being passed in to AddJwtBearer contains an Events property of its own, which allows you to customize various parts of the process. You need to use MessageReceived Event for the same

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => {
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    context.Token = context.Request.Cookies["CookieName"];
                    return Task.CompletedTask;
                }
            };
        });
}

Using HTTP cookie with asp.net core

Uncritical answered 29/6, 2022 at 8:3 Comment(2)
And what should be the "CookieName"?Distasteful
Oh nothing, I figured it out! Thank youDistasteful

© 2022 - 2024 — McMap. All rights reserved.