asp.netasp.net-mvcasp.net-corejwtcookie-authentication

ASP .Net Core, Store JWT in Cookie


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

Solution

  • 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