Skip to content

Instantly share code, notes, and snippets.

@mausworks
Last active February 22, 2018 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mausworks/56d81435215e62bf0971285b30345d9f to your computer and use it in GitHub Desktop.
Save mausworks/56d81435215e62bf0971285b30345d9f to your computer and use it in GitHub Desktop.
A functional helper class for Basic authentication. For tests, check out: https://gist.github.com/mausworks/37ba3aa9d3aeb3625b2eda196a0f1796
public class BasicAuthentication
{
public const string Scheme = "Basic";
public const char DelimiterSymbol = ':';
public string Username { get; }
public string Password { get; }
private string _base64;
public BasicAuthentication(string username, string password)
{
AssertNotNull(username, password);
Username = username;
Password = password;
}
public string GetBase64(Encoding encoding)
{
if (_base64 == null)
{
var bytes = encoding.GetBytes(Combine(Username, Password));
_base64 = Convert.ToBase64String(bytes);
}
return _base64;
}
public static BasicAuthentication FromBase64(string base64, Encoding encoding)
{
var auth = encoding.GetString(Base64Bytes(base64))
.Split(DelimiterSymbol);
return new BasicAuthentication(auth[0], auth[1])
{
_base64 = base64
};
}
public static string Combine(string username, string password)
=> $"{username}{DelimiterSymbol}{password}";
private void AssertNotNull(string username, string password)
{
if (username == null)
{
throw new ArgumentNullException(nameof(username));
}
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
}
private static byte[] Base64Bytes(string base64)
=> Convert.FromBase64String(base64);
}
@kiquenet
Copy link

OAuth2 alternative ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment