In ASP.NET Core read JWT token from Cookie instead of Headers

后端 未结 1 1567
长情又很酷
长情又很酷 2021-01-02 07:33

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

相关标签:
1条回答
  • 2021-01-02 08:14

    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.

    0 讨论(0)
提交回复
热议问题