.NET Core 2.1中的HttpContext.GetTokenAsync无法检索JWT [英] JWT cannot be retrieved by HttpContext.GetTokenAsync in .NET Core 2.1

查看:906
本文介绍了.NET Core 2.1中的HttpContext.GetTokenAsync无法检索JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这真的让我挠头,因为我可以创建JWT.我可以添加一个属性来授权控制器,然后查看是否不向标题添加"Authorization""Bearer(token)",它将返回未经授权的401.但是,像获取令牌的字符串来获取其有效负载声明这样的简单操作是行不通的.

This one really has me scratching my head as I can create a JWT. I can add an attribute to authorize a controller and see if I do not add an 'Authorization' 'Bearer (token)' to a header it will return a 401 unauthorized. However something as simple as getting the string of the token to get it's payload claims is not working.

这很好用:

var token = Request.Headers["Authorization"];

这不是:

var token2 = await HttpContext.GetTokenAsync(JwtBearerDefaults.AuthenticationScheme, "access_token");

我更改了签名,像这样在启动时连接了IHTTPContextAccessor:

I have change the signature, hooked up the IHTTPContextAccessor in startup like so:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

我可以看到IHttpContextAccessor具有值以及授权密钥.我本可以发誓过去在.NET Core 2.0中可以轻松工作,但现在却不行.我在启动"或程序"中缺少一个简单的连接吗?此时,我将仅从Request.Headers中获取数据.但这就像黑客一样.

I can see that the IHttpContextAccessor has values, as well as the authorization key. I could have sworn this used to work easily in .NET Core 2.0 and now it doesn't. Is there a simple hookup I am missing in Startup or Program? At this point I am going to just get the data from Request.Headers. But that just feels like a hack.

推荐答案

这似乎是 ASP.NET Core 2.1(即将在2.2版中修复)中的已知问题.我链接的GitHub问题的建议是,就像您在问题中所做的那样,仅从标头中提取值.一旦2.2发布并可以升级,您应该可以恢复使用HttpContext.GetTokenAsync.

This appears to be a known issue in ASP.NET Core 2.1 (fixed in the upcoming 2.2). The suggestion on the GitHub issue I've linked is to just extract the value from the header, as you're doing in your question. Once 2.2 is released and you're able to upgrade, you should be able to revert to using HttpContext.GetTokenAsync.

这篇关于.NET Core 2.1中的HttpContext.GetTokenAsync无法检索JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆