如何在aspnet.core Web API中验证JWT令牌? [英] How to validate JWT Token in aspnet.core web api?
问题描述
我创建了自定义中间件类,用于验证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()
};
});
(使用上面的链接查看 GetSymmetricSecurityKey $ c的实现$ c>,
GetValidAudience
, GetValidIssuer
扩展方法)
(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屋!