parse authorization headers in csharp

To parse the Authorization header in C#, you can access the HttpRequest.Headers property of the current HttpContext object. The Authorization header is stored in this collection under the key "Authorization". Here's an example of how to extract the token from a Bearer token based authorization header:

main.cs
using Microsoft.AspNetCore.Http;
using System.Linq;

public static string ExtractTokenFromAuthorizationHeader(HttpContext context)
{
    var authorizationHeader = context.Request.Headers["Authorization"].FirstOrDefault();
    if (authorizationHeader != null && authorizationHeader.StartsWith("Bearer "))
    {
        return authorizationHeader.Substring("Bearer ".Length);
    }

    return null;
}
400 chars
14 lines

You can then call this method passing in the current HttpContext to extract the token from the Authorization header. Note that this example assumes that the Authorization header starts with "Bearer ". If you're using a different authorization scheme, you'll need to adjust the code accordingly.

gistlibby LogSnag