JWT cannot be retrieved by HttpContext.GetTokenAsync in .NET Core 2.1

给你一囗甜甜゛ 提交于 2019-11-28 04:09:41

问题


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.

So this works fine:

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

This does not:

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

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

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

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.


回答1:


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.



来源:https://stackoverflow.com/questions/52793488/jwt-cannot-be-retrieved-by-httpcontext-gettokenasync-in-net-core-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!