Skip to content

Instantly share code, notes, and snippets.

@jgauffin
Created January 13, 2015 12:03
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 jgauffin/e5f5693849287d70942f to your computer and use it in GitHub Desktop.
Save jgauffin/e5f5693849287d70942f to your computer and use it in GitHub Desktop.
Basic http authentication with Griffin framework
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Griffin.Net.Channels;
using Griffin.Net.Protocols.Http;
using Griffin.Net.Protocols.Http.Serializers;
using HttpListener = Griffin.Net.Protocols.Http.HttpListener;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
var listener = new HttpListener();
listener.BodyDecoder = new UrlFormattedMessageSerializer();
listener.MessageReceived += OnMessage;
listener.Start(IPAddress.Any, 1234);
Console.ReadLine();
}
private static void OnMessage(ITcpChannel channel, object message)
{
var request = (HttpRequest)message;
if (!Authenticate(channel, request))
return;
//authenticated here.
}
private static bool Authenticate(ITcpChannel channel, HttpRequest request)
{
if (channel.Data["Authenticated"] != null)
{
Thread.CurrentPrincipal =
new GenericPrincipal(new GenericIdentity((string)channel.Data["Authenticated"]), new string[0]);
return true;
}
var authenticateHeader = request.Headers["Authorization"];
if (authenticateHeader != null)
{
var bytes = Convert.FromBase64String(authenticateHeader);
var parts = Encoding.ASCII.GetString(bytes).Split(';');
var username = parts[0];
var password = parts[1];
//TODO: validate user
channel.Data["Authenticated"] = username;
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), new string[0]);
return true;
}
var response = request.CreateResponse();
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.AddHeader("WWW-Authenticate", "Basic realm=yoursite.net");
channel.Send(response);
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment