ASP.NET Core中的承载令牌身份验证

编程入门 行业动态 更新时间:2024-10-20 03:41:32
本文介绍了ASP.NET Core中的承载令牌身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尝试在简单的.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中的承载令牌身份验证

本文发布于:2023-11-17 02:11:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   身份验证   ASP   NET   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!