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

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

问题描述

这个真的让我摸不着头脑,因为我可以创建一个 JWT.我可以添加一个属性来授权控制器,看看我是否不向标头添加授权"承载(令牌)",它将返回未经授权的 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天全站免登陆