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

10,797

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.

Share:
10,797
djangojazz
Author by

djangojazz

I love technology and music. I am advanced at TSQL and also like to try to create in C# 3.5 through 4.6.2 when I can. I tend to favor Data Access with Linq, Entity Framework, ADO.NET, and SQL being my strong points. But I also dab in WPF and Prism and sometimes WinForms when forced to. I like all technologies really and wish there was more time in the day to do everything I want to learn but having kids and a full time job slows you down a little bit.

Updated on June 15, 2022

Comments

  • djangojazz
    djangojazz almost 2 years

    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.

  • djangojazz
    djangojazz over 5 years
    Yeah I looked up the link you gave and tried Haok's long winded thing like: (await _httpContextAccessor.HttpContext.AuthenticateAsync(JwtBearer‌​Defaults.Authenticat‌​ionScheme)).Ticket.P‌​roperties.GetTokenVa‌​lue("access_token"); That still doesn't work even with wiring up the HttpContextAccessor in the controller and in the IOC of the startup. Glad it's not just me doing something wrong. That's weird they broke something like that though when I have stumbled upon more than a few sites that suggest that the 'HttpContext.GetTokenAsync'. Guess I will just stick with getting the header, thanks.
  • Kirk Larkin
    Kirk Larkin over 5 years
    Tratcher confirms further down in the chain that HaoK's approach doesn't work too, FYI.