I am porting an ASP.NET Web API 4.6 OWIN
application to ASP.NET Core 2.1
. The application is working based on JWT
token. But the token
In ASP.NET Core 2.0, the authentication system was somewhat overhauled. Rather than using e.g. UseJwtBearerAuthentication
as middleware, ASP.NET Core 2.0+ configures things using DI. For example, this looks something like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options => {
// ...
});
}
With that out of the way, the next question would be: how do we instruct the JwtBearer authentication process to look at a cookie using this new system?
That options
object being passed in to AddJwtBearer
contains an Events
property of its own, which allows you to customise various parts of the process. Using OnMessageReceived
, you can achieve what you're looking for:
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;
}
};
});
}
By setting context.Token
, you're telling the JwtBearer process that you've taken care of extracting the token yourself.
Here's a useful migration document that explains the authentication changes in more detail.