1 Comment

ASP.NET Core 3.1 JWT Cookie Authentication

JWT Authentication in ASP.NET Core 3.1 is very easy to implement with native support, which allows you to authorize endpoints without any extra dependencies. The middleware handles all the hard work, and all you have to do is add a few lines of code! However, there is one bit of documentation that may not be as obvious. How do you get the middleware to check the request cookies instead of the header?

Sometimes, when building a web app, you don’t want your client to handle the bearer token manually. It can be easier to persist information in a secure cookie. To take advantage of the existing .NET Core JWT middleware and use cookies, this simple trick will get you going on the right path.

(If you’re looking for information on how to set up JWT in your project, check out this tutorial.)

Inside your Startup.cs file, find where you registered the JWT authentication schema with the AddAuthentication method. The JWT bearer option AddJWTBearer(options) gives you the ability to access its Events. Add the following Event to your options:


options.Events = new JwtBearerEvents
{
  OnMessageReceived = context =>
  {
    context.Token = context.Request.Cookies["your-cookie"];
    return Task.CompletedTask;
  },
};

Now when the middleware receives a “message,” it will run the Event. This Event looks at the message’s cookies and sets the MessageReceivedContext Token to the cookie you specified. This will override the default, which would be pulling the token from the message’s headers.

Putting it all together, your AddAuthentication method should look something like this:


public void ConfigureServices(IServiceColleciton serivces)
{
  services.AddAuthentication(configureOptions =>
  {
    configureOptions.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
  })
  .AddJwtBearer(options => 
  {
    options.TokenValidationParameters = new TokenValidationParameters
    {
      ValidateIssuerSigningKey = true,
      IssuerSigningKey = new SymmetricSecurityKey(key),
      ValidateIssuer = true,
      ValidIssuer = issuer,
      ValidateAudience = true,
      ValidAudience = audience,
      ValidateLifetime = true,
    };
    options.Events = new JwtBearerEvents
    {
      OnMessageReceived = context =>
      {
        context.Token = context.Request.Cookies["your-cookie"];
        return Task.CompletedTask;
      };
    }
  }
});

Now you can take full advantage of the .NET Core JWT middleware without being forced to use the request headers.