-
-
Save thecodeite/9322107 to your computer and use it in GitHub Desktop.
HTTP Authorisation module
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
public class BasicAuth : IHttpModule | |
{ | |
protected bool IsHeaderPresent | |
{ | |
get | |
{ | |
var context = HttpContext.Current; | |
var authHeader = context.Request.Headers["Authorization"]; | |
return (!string.IsNullOrEmpty(authHeader)); | |
} | |
} | |
#region IHttpModule Members | |
public void Init(HttpApplication context) | |
{ | |
context.AuthenticateRequest += Check; | |
context.EndRequest += EndRequest; | |
} | |
public void Dispose() | |
{ | |
} | |
#endregion | |
void EndRequest(object sender, EventArgs e) | |
{ | |
if (HttpContext.Current.Response.StatusCode == 401) | |
SendAuthHeader(); | |
} | |
void SendAuthHeader() | |
{ | |
var context = HttpContext.Current; | |
context.Response.StatusCode = 401; | |
context.Response.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"hardcoded\"")); | |
} | |
void Check(object sender, EventArgs e) | |
{ | |
if (!AuthenticateUser()) | |
DenyAccess(); | |
} | |
void DenyAccess() | |
{ | |
var context = HttpContext.Current; | |
context.Response.StatusCode = 401; | |
context.Response.End(); | |
} | |
bool AuthenticateUser() | |
{ | |
IDictionary<string, string> users = new Dictionary<string, string>() | |
{ | |
{ "magic", "socks" } | |
}; | |
var authHeader = HttpContext.Current.Request.Headers["Authorization"]; | |
if (authHeader != null && authHeader.StartsWith("Basic")) | |
{ | |
// Extract credentials from header | |
var credentials = ExtractCredentials(authHeader); | |
var username = credentials[0]; | |
var password = credentials[1]; | |
if (users.ContainsKey(username) && users[username] == password) | |
{ | |
SetPrincipal(username); | |
return true; | |
} | |
} | |
return false; | |
} | |
// Create GenericPrincipal and set it on Context.User | |
static void SetPrincipal(string username) | |
{ | |
//Create Principal and set Context.User | |
var id = new GenericIdentity(username, "BasicAuth"); | |
var p = new GenericPrincipal(id, null); | |
HttpContext.Current.User = p; | |
} | |
string[] ExtractCredentials(string authHeader) | |
{ | |
// Strip out the "basic" | |
var encodedUserPass = authHeader.Substring(6).Trim(); | |
// That's the right encoding | |
var encoding = Encoding.GetEncoding("iso-8859-1"); | |
var userPass = encoding.GetString(Convert.FromBase64String(encodedUserPass)); | |
var separator = userPass.IndexOf(':'); | |
var credentials = new string[2]; | |
credentials[0] = userPass.Substring(0, separator); | |
credentials[1] = userPass.Substring(separator + 1); | |
return credentials; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment