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.
JWT cannot be retrieved by HttpContext.GetTokenAsync in .NET Core 2.1 0 Jwt Role authentication in controller ASP.net core 2.1 0 ASP .NET CORE 2.2 JWT & Claims identity Authentication for Website 1 Can't get asp .net core 2.2 to validate my JWT 0
Here I did use the same JWT Authentication in .NET Core technique to secure the method and then followed by another API to fetch the access token programmatically to pass it to other components as required. The below piece of code is from the same sample which we learned in
That’s all, Finally, we found it is very simple to read access token from HttpContext in .NET Core. Happy Coding!! Do you have any comments or ideas or any better suggestions to share?
ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service. The Razor Pages PageModel exposes the HttpContext property:
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With