如何在aspnet.core Web API中验证JWT令牌?

Gir*_*ish 5 c# asp.net-web-api2 .net-core asp.net-core-webapi asp.net-core-2.0

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

我想知道我应该添加到配置服务中以使用JWT验证Web API的哪些内容?我在控制器类中添加了[授权]

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

 app.UseAuthentication();
 app.MessageHandlerMiddleware();
 app.UseMvc();
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*man 4

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

\n\n

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

\n\n

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

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

GetSymmetricSecurityKey(使用上面的链接查看、GetValidAudienceGetValidIssuerext. 方法的实现)

\n\n

还有非常重要的部分:

\n\n
services.AddAuthorization(auth =>\n{\n    auth\n    .AddPolicy(\n        _configuration.GetDefaultPolicy(),\n        new AuthorizationPolicyBuilder()\n            .AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme\xe2\x80\x8c\xe2\x80\x8b)\n            .RequireAuthenticatedUser().Build()\n    );\n});\n
Run Code Online (Sandbox Code Playgroud)\n