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.
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.
The command requires the valid user name and password (or API token) in the application to which you want to connect, and it encodes the credentials with base64. In the Authorization Header field, you enter the word "Basic" (which is the Authorization header type), a space, and then the base64-encoded credentials.
You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter.
The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.
Basic Auth: The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send.
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...
}
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