Skip to content

Instantly share code, notes, and snippets.

@gyuwon
Created December 11, 2018 10:01
Show Gist options
  • Save gyuwon/799573061113551aec6e4aaf5f8bfa33 to your computer and use it in GitHub Desktop.
Save gyuwon/799573061113551aec6e4aaf5f8bfa33 to your computer and use it in GitHub Desktop.
Extract credentials from basic authentication header.
// Although this function works it may not be the best way and has some bug.
bool TryGetBasicAutheticationCredentials(string authorizationHeader, out string username, out string password)
{
const string schemePrefix = "Basic ";
if (authorizationHeader != null &&
authorizationHeader.StartsWith(schemePrefix, System.StringComparison.OrdinalIgnoreCase))
{
try
{
string authorizationValue = authorizationHeader.Substring(schemePrefix.Length);
byte[] credentialsBytes = System.Convert.FromBase64String(authorizationValue);
string credentials = System.Text.Encoding.UTF8.GetString(credentialsBytes);
string[] tokens = credentials.Split(':');
username = tokens[0];
password = tokens[1];
return true;
}
catch
{
}
}
username = default;
password = default;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment