Last active
August 29, 2015 14:01
-
-
Save thomaslevesque/c50cb07f1947cd84e5da to your computer and use it in GitHub Desktop.
A Basic authentication module that uses UTF-8 to encode username and password (rather than ANSI for the built-in implementation)
This file contains hidden or 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
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Text; | |
using Sharebox.Utils.Collections; | |
namespace Sharebox.Communication | |
{ | |
class BasicAuthenticationModule : IAuthenticationModule | |
{ | |
public static bool ReplaceDefault() | |
{ | |
var basicClient = AuthenticationManager.RegisteredModules.AsEnumerable() | |
.OfType<IAuthenticationModule>() | |
.FirstOrDefault(m => m.AuthenticationType == "Basic"); | |
if (basicClient != null && !(basicClient is BasicAuthenticationModule)) | |
{ | |
AuthenticationManager.Unregister(basicClient); | |
AuthenticationManager.Register(new BasicAuthenticationModule(basicClient)); | |
return true; | |
} | |
return false; | |
} | |
private readonly IAuthenticationModule _basicClient; | |
public BasicAuthenticationModule(IAuthenticationModule basicClient) | |
{ | |
_basicClient = basicClient; | |
} | |
public Authorization Authenticate(string challenge, WebRequest request, ICredentials credentials) | |
{ | |
var auth = _basicClient.Authenticate(challenge, request, credentials); | |
return FixEncoding(auth); | |
} | |
public Authorization PreAuthenticate(WebRequest request, ICredentials credentials) | |
{ | |
var auth = _basicClient.PreAuthenticate(request, credentials); | |
return FixEncoding(auth); | |
} | |
// The default Basic auth module encodes the username/password in ANSI | |
// Change it to use UTF-8 instead | |
private Authorization FixEncoding(Authorization auth) | |
{ | |
const string prefix = "Basic "; | |
if (auth != null && auth.Complete && auth.Message != null && auth.Message.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
try | |
{ | |
var bytes = Convert.FromBase64String(auth.Message.Substring(prefix.Length)); | |
string userAndPass = Encoding.Default.GetString(bytes); | |
bytes = Encoding.UTF8.GetBytes(userAndPass); | |
string message = prefix + Convert.ToBase64String(bytes); | |
auth = new Authorization(message, auth.Complete, auth.ConnectionGroupId); | |
} | |
catch(FormatException) | |
{ | |
} | |
} | |
return auth; | |
} | |
public bool CanPreAuthenticate { get { return true; } } | |
public string AuthenticationType { get { return "Basic"; } } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment