Search code examples
c#asp.net.nethttpasp.net-core

What's the simplest way to fetch the value of the Authorization header of a request?


Question

Given an HttpRequest with an Authorization header, what's the simplest way to fetch the authentication type and the authentication credentials of said header?

As an example, given Authorization: Bearer YWxhZGRpbjpvcGVuc2VzYW1l, how can I get both Bearer and YWxhZGRpbjpvcGVuc2VzYW1l from an HttpRequest?

Yes, I'm aware that the Identity framework exists. I'm not using it here. If you really want to try and change my mind we can discuss it in chat.

What I tried

I'm writing a function along the lines of:

var authorizationHeader = request.Headers["Authorization"].ToArray()[0];
var authorizationParts = authorizationHeader.Split(' ');
if (authorizationParts.Length == 2 && authorizationParts[0] == "Bearer")
{
    var tokenValue = authorizationParts[1];
    // ...
}
// ...

but it's very error prone and verbose. For example in the first line I haven't checked if the array contains at least one element.


Solution

  • Here's some simple middleware that will do it:

    app.Use(async (context, next) =>
    {
        if (context.Request.Headers.ContainsKey("Authorization") &&
            context.Request.Headers["Authorization"][0].StartsWith("Bearer "))
        {
            var token = context.Request.Headers["Authorization"][0]
                .Substring("Bearer ".Length);
            //do stuff...
        }
    
        await next.Invoke();
    });
    

    Personally though I would be less concerned with verbosity, move the above to an extension and make it more verbose, e.g. by being more explicit about what you're doing:

    if (!context.Request.Headers.ContainsKey("Authorization"))
        throw new SomeException(); //or whatever
    
    var authHeader = context.Request.Headers["Authorization"][0];
    if (authHeader.StartsWith("Bearer "))
    {
        var token = authHeader.Substring("Bearer ".Length);
        //do stuff...
    }