ASP.NET核心中的持证人令牌认证
尝试在简单的.Net Core Web API项目中使用基于持证者令牌的身份验证。 这是我的Startup.cs
app.UseMvc();
//---
const string secretKey = "mysupersecret_secretkey!123";
SymmetricSecurityKey signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
SigningCredentials signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
//---
const string audience = "Audience";
const string issuer = "Issuer";
//---
TokenValidationParameters tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = false,
ValidIssuer = issuer,
ValidateAudience = true,
ValidAudience = audience,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
AuthenticationType = JwtBearerDefaults.AuthenticationScheme
};
//---
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
});
另外我将AuthorizeAttribute
添加到控制器操作中
[HttpGet]
[Authorize(ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public IEnumerable<string> Get()
{
return new[] { "value1", "value2" };
}
但是,当试图发送请求与头Authorization: Bearer [TOKEN]
我得到异常
System.InvalidOperationException: No authentication handler is configured to authenticate for the scheme: Bearer
at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.
那么这个“身份验证处理程序”是什么? 我需要设置这个处理程序?
在ASP.NET Core中,中间件的顺序很重要:它们以与注册顺序相同的顺序执行。 这里, app.UseMvc()
在JWT承载中间件之前被调用,所以这是行不通的。
将app.UseMvc()
放在管道末端,它应该可以工作:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme,
});
app.UseMvc();
链接地址: http://www.djcxy.com/p/22439.html