【问题标题】:How to validate JWT Token in aspnet.core web api?如何在 aspnet.core Web api 中验证 JWT 令牌?
【发布时间】:2019-01-27 08:23:10
【问题描述】:

我创建了验证 JWT 令牌的自定义中间件类。我在配置方法中app.AddMvc() 之前调用此方法。 ***

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

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

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

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

【问题讨论】:

  • 为 JWT 验证创建“自定义中间件类”的原因是什么?您是否有不能使用内置验证过程的特定原因?
  • 坦率地说,我不知道如何使用内置的验证过程来验证它!因此,我创建了自己的身份验证材料
  • 阅读Securing ASP.NET Core 2.0 Applications with JWTs 看看是否有帮助。
  • 感谢基里克·拉金。让我检查一下

标签: c# .net-core asp.net-web-api2 asp.net-core-2.0 asp.net-core-webapi


【解决方案1】:

one of my answers,您可以看到我们如何传递 JWT 令牌以及代码如何查找经典 .NET(非核心)ASP.NET WebAPI 2。

差别不大,ASP.NET Core 的代码看起来差不多。

关键方面是 - 当您在 Startup 中添加 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.方法的实现)

也是很重要的部分:

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

【讨论】:

    猜你喜欢
    • 2021-11-16
    • 1970-01-01
    • 2023-02-24
    • 2019-05-01
    • 1970-01-01
    • 2021-12-16
    • 2018-10-16
    • 2021-06-27
    • 2020-10-12
    相关资源
    最近更新 更多