尝试在简单的.Net Core Web API项目中使用基于承载令牌的身份验证.这是我的Startup.cs
Trying to use bearer token based authentification in simple .Net Core Web API project. Here is my 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添加到控制器操作中
Also i add AuthorizeAttribute to controllers action
[HttpGet] [Authorize(ActiveAuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public IEnumerable<string> Get() { return new[] { "value1", "value2" }; }但是当尝试发送带有标头的get请求时 Authorization: Bearer [TOKEN] 我得到例外
But when try to send get request with header Authorization: Bearer [TOKEN] i get exception
System.InvalidOperationException: No authentication handler is configured to authenticate for the scheme: Bearer at Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager.那么这个身份验证处理程序"是什么?我需要在哪里设置此处理程序?
So what is this 'authentication handler'? Where i need to set this handler?
推荐答案在ASP.NET Core中,中间件的顺序很重要:它们以与注册时相同的顺序执行.在这里,app.UseMvc()在JWT承载中间件之前被调用,所以这是行不通的.
In ASP.NET Core, the order of the middleware matters: they are executed in the same order as they are registered. Here, app.UseMvc() is called before the JWT bearer middleware, so this can't work.
将app.UseMvc()放在管道的末端,它应该可以工作:
Put app.UseMvc() at the end of your pipeline and it should work:
app.UseJwtBearerAuthentication(new JwtBearerOptions { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = tokenValidationParameters, AuthenticationScheme = JwtBearerDefaults.AuthenticationScheme, }); app.UseMvc();更多推荐
ASP.NET Core中的承载令牌身份验证
发布评论