Created
January 13, 2016 14:04
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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