Skip to content

Instantly share code, notes, and snippets.

@formix
Last active March 30, 2016 01:27
Show Gist options
  • Save formix/f684039b579a73855b87441d080d961d to your computer and use it in GitHub Desktop.
Save formix/f684039b579a73855b87441d080d961d to your computer and use it in GitHub Desktop.
.NET Custom Basic Authentication
using System;
using System.IO;
using System.Text;
using System.Web;
namespace BasicAuthenticationFlashTalk
{
public class BasicAuthenticationModule : IHttpModule
{
private const string REALM = "Private";
public void Init(HttpApplication context)
{
context.AuthenticateRequest += context_AuthenticateRequest;
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication context = (HttpApplication)sender;
if (!this.Authenticate(context.Request))
{
context.Response.Clear();
context.Response.StatusCode = 401;
context.Response.StatusDescription = "Authentication required";
context.Response.AddHeader("WWW-Authenticate", "Basic realm=\"" + REALM + "\"");
// I hate .NET when I need to do something like that:
context.Response.SuppressFormsAuthenticationRedirect = true;
}
}
private bool Authenticate(HttpRequest httpRequest)
{
string auth = httpRequest.Headers["Authorization"];
if (auth == null)
{
return false;
}
string b64data = auth.Substring(6).Trim();
byte[] data = Convert.FromBase64String(b64data);
string credentials = Encoding.Default.GetString(data);
string[] userpass = credentials.Split(':');
string user = userpass[0];
string pass = userpass[1];
string internalHashedPass = this.GetUserPasswordHash(user);
if (internalHashedPass == null)
{
return false;
}
string internalSalt = this.GetUserSalt(user);
string hashedPass = this.HashPassword(internalSalt, pass);
return internalHashedPass == hashedPass;
}
private string GetUserPasswordHash(string userName) {
return "123456789";
}
private string HashPassword(string salt, string password)
{
return password;
}
private string GetUserSalt(string user)
{
return user;
}
public void Dispose()
{
}
}
}
/* This is the corresponding Web.config to register the module:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="CustomBasicAuthenticationModule" type="BasicAuthenticationFlashTalk.BasicAuthenticationModule, BasicAuthenticationFlashTalk" />
</modules>
</system.webServer>
</configuration>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment