Skip to content

Instantly share code, notes, and snippets.

@cogree
Created January 13, 2016 14:04
Show Gist options
  • Save cogree/d0b80d9c7d6e17a9fff6 to your computer and use it in GitHub Desktop.
Save cogree/d0b80d9c7d6e17a9fff6 to your computer and use it in GitHub Desktop.
Provided the value of an "Authorization" header, you will get a bool result and the username and password if successful.
public static bool TryParseBasicAuthentication(string header, out string username, out string password)
{
username = null; password = null;
try
{
if (!header.StartsWith("Basic "))
return false;
// Remove the scheme and optional space after colon if present.
header = header.Replace("Basic", "").TrimStart();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
const char separator = ':';
string unencodedAuth = encoding.GetString(Convert.FromBase64String(header));
if (!unencodedAuth.Contains(separator))
return false;
int separatorIndex = unencodedAuth.IndexOf(separator);
username = unencodedAuth.Substring(0, separatorIndex);
password = unencodedAuth.Substring(separatorIndex + 1);
return true;
}
catch
{
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment