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.
There are not many differences, the code for ASP.NET Core looks similar.
The key aspect is - when you add JWT config in Startup the app handles validation automatically.
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()
};
});
(use the above link to see the implementation of GetSymmetricSecurityKey
, GetValidAudience
, GetValidIssuer
ext. methods)
Also very important part:
services.AddAuthorization(auth =>
{
auth
.AddPolicy(
_configuration.GetDefaultPolicy(),
new AuthorizationPolicyBuilder()
.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme??)
.RequireAuthenticatedUser().Build()
);
});
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…