在 ASP.NET Core 中,从 Cookie 而不是 Headers 中读取 JWT 令牌

时间:2023-03-29
本文介绍了在 ASP.NET Core 中,从 Cookie 而不是 Headers 中读取 JWT 令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在将 ASP.NET Web API 4.6 OWIN 应用程序移植到 ASP.NET Core 2.1.该应用程序基于 JWT 令牌工作.但是通过 cookie 而不是标头传递的令牌.我不确定为什么不使用标题,这只是我必须处理的情况.

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 passed via cookie instead of header. I'm not sure why headers are not used, it is just the situation that I have to deal with.

考虑到身份验证不是通过 cookie 完成的.cookie 仅用作传输媒体.在遗留应用程序中,CookieOAuthBearerProvider 用于从 cookie 中提取 JWT 令牌.配置代码如下:

Consider that authentication is not done via cookie. The cookie is just used as a transfering media. In the legacy application CookieOAuthBearerProvider is employed to extract JWT token from cookie. Configuration code is as like this:

    app.UseJwtBearerAuthentication(
        new JwtBearerAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new[] { audienceId },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
            },
            Provider = new CookieOAuthBearerProvider("token")
        });
}

CookieOAuthBearerProvider类源码如下:

public class CookieOAuthBearerProvider : OAuthBearerAuthenticationProvider
{
    readonly string _name;
    public CookieOAuthBearerProvider(string name)
    {
        _name = name;
    }

    public override Task RequestToken(OAuthRequestTokenContext context)
    {
        var value = context.Request.Cookies[_name];

        if (!string.IsNullOrEmpty(value))
        {
            context.Token = value;
        }

        return Task.FromResult<object>(null);
    }

这里讨论了这个解决方案详细.

This solution is discussed here with more detail.

现在我需要为 ASP.NET Core 实现类似的解决方案.问题是 UseJwtBearerAuthentication 不再存在于 ASP.NET Core 中,我不知道如何引入自定义 AuthenticationProvider.

Now I need to implement similar solution for ASP.NET Core. Problem is that UseJwtBearerAuthentication does not exists in ASP.NET Core anymore and I do not know how I can introduce a custom AuthenticationProvider.

非常感谢任何帮助.

更新:有 一种尝试通过自己的代码验证 JWT 的解决方案.这不是我需要的.我只是在寻找一种方法,将从 cookie 收到的令牌传递给标头阅读器.

UPDATE: There is a solution that tries to validate JWT by its own code. It is not what I need. I'm just searching for a way to pass token recieved from cookie to header reader.

推荐答案

在 ASP.NET Core 2.0 中,身份验证系统进行了一些大修.而不是使用例如UseJwtBearerAuthentication 作为中间件,ASP.NET Core 2.0+ 使用 DI 进行配置.例如,这看起来像这样:

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 => {
            // ...
        });
}

除此之外,下一个问题是:我们如何指示 JwtBearer 身份验证过程使用这个新系统查看 cookie?

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?

传递给 AddJwtBeareroptions 对象包含自己的 Events 属性,它允许您自定义流程的各个部分.使用 OnMessageReceived,您可以实现您想要的:

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

通过设置 context.Token,您是在告诉 JwtBearer 进程您已经负责自己提取令牌.

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.

这篇关于在 ASP.NET Core 中,从 Cookie 而不是 Headers 中读取 JWT 令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:隐藏使用 RS256 PII 的 JWT SecurityTokenInvalidSignatureException 下一篇:ASP.NET 核心 JWT 身份验证总是抛出 401 未授权

相关文章