如何在 aspnet.core web api 中验证 JWT 令牌? [英] How to validate JWT Token in aspnet.core web api?

查看:26
本文介绍了如何在 aspnet.core web api 中验证 JWT 令牌?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了自定义中间件类来验证 JWT 令牌.我在 configure 方法中的 app.AddMvc() 之前调用这个方法.***

I have created custom middleware class which validates the JWT token. I am calling this method before app.AddMvc() in configure method. ***

我想知道我应该向配置服务添加哪些内容以使用 JWT 对我的 Web API 进行身份验证?我在我的 Controller 类中添加了 [Authorize]

I would like to know what are the things that I should add to Configuration services to authenticate my web API using JWT? I have added [Authorize] in my Controller class

我是否需要调用我的中间件类来首先在 Configure 方法中验证 JWT 令牌?或者我应该调用 App.UseAuthentication()我使用以下顺序:

Do I need to call my middleware class which validates the JWT token first in Configure method? or I should call App.UseAuthentication() I am using the following order :

 app.UseAuthentication();
 app.MessageHandlerMiddleware();
 app.UseMvc();

<小时>

我是 .net Web API 实现的新手.你能帮我吗?


I am new to .net web API implementation. Could you please help me out?

推荐答案

我的一个回答你可以看到如何我们传递 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()
    );
});

这篇关于如何在 aspnet.core web api 中验证 JWT 令牌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆