且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 aspnet.core web api 中验证 JWT 令牌?

更新时间:2023-02-16 15:29:19

我的一个回答你可以看到如何我们传递 JWT 令牌以及代码如何查找经典 .NET(非核心)ASP.NET WebAPI 2.

From one of my answers you can see how we pass JWT token and how the code looks for classic .NET (non-core) ASP.NET WebAPI 2.

没有太多区别,ASP.NET Core 的代码看起来很相似.

There are not many differences, the code for ASP.NET Core looks similar.

关键方面是 - 当您在启动时添加 JWT 配置时,应用程序会自动处理验证.

services
    .AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            IssuerSigningKey = _configuration.GetSymmetricSecurityKey(),
            ValidAudience = _configuration.GetValidAudience(),
            ValidIssuer = _configuration.GetValidIssuer()
        };
    });

(使用上面的链接查看GetSymmetricSecurityKeyGetValidAudienceGetValidIssuer ext.method的实现)

(use the above link to see the implementation of GetSymmetricSecurityKey, GetValidAudience, GetValidIssuer ext. methods)

也是非常重要的部分:

services.AddAuthorization(auth =>
{
    auth
    .AddPolicy(
        _configuration.GetDefaultPolicy(),
        new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme‌​)
            .RequireAuthenticatedUser().Build()
    );
});