Here is a clever way to get the header without having to go in to the headers dictionary. This will also let the framework parse the token, which is what I believe you are looking for:
[HttpGet, Route("someEndpoint")]
public IActionResult SomeEndpoint([FromHeader] string authorization)
{
if(AuthenticationHeaderValue.TryParse(authorization, out var headerValue))
{
// we have a valid AuthenticationHeaderValue that has the following details:
var scheme = headerValue.Scheme;
var parameter = headerValue.Parameter;
// scheme will be "Bearer"
// parmameter will be the token itself.
}
return Ok();
}
You can also grab the header the old-school way:
[HttpGet, Route("someEndpoint")]
public IActionResult SomeEndpoint()
{
var authorization = Request.Headers[HeaderNames.Authorization];
if (AuthenticationHeaderValue.TryParse(authorization, out var headerValue))
{
// we have a valid AuthenticationHeaderValue that has the following details:
var scheme = headerValue.Scheme;
var parameter = headerValue.Parameter;
// scheme will be "Bearer"
// parmameter will be the token itself.
}
return Ok();
}
What's nice is AuthenticationHeaderValue.TryParse
will cover oddball cases like if there is more than once space between the scheme and the token, or if there are spaces before the scheme, or spaces after the token... and trim it up for you.
Now, those cases should never happen, but... they may, and the execution of accessTokenWithBearerPrefix.Substring("Bearer ".Length);
would fail. Which is why I believe you wanted a more concrete way of parsing the token.