Skip to content

Instantly share code, notes, and snippets.

@pmhsfelix
Last active November 22, 2016 16:25
Show Gist options
  • Save pmhsfelix/6148160 to your computer and use it in GitHub Desktop.
Save pmhsfelix/6148160 to your computer and use it in GitHub Desktop.
Katana based HTTP Basic Authentication middleware, mostly for learning purposes
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Owin;
using WebApiBook.Security.Common;
namespace WebApiBook.Security.AuthN
{
class BasicAuthnMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
public BasicAuthnMiddleware(OwinMiddleware next, BasicAuthenticationOptions options)
: base(next, options)
{
}
protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
{
return new BasicAuthenticationHandler();
}
}
public class BasicAuthenticationOptions : AuthenticationOptions
{
public Func<string, string, Task<AuthenticationTicket>> ValidateCredentials { get; set; }
public string Realm { get; set; }
public BasicAuthenticationOptions()
: base("Basic"){ }
}
public static class BasicAuthnMiddlewareExtensions
{
public static IAppBuilder UseBasicAuthentication(this IAppBuilder app, BasicAuthenticationOptions options)
{
return app.Use(typeof(BasicAuthnMiddleware), options);
}
}
class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
var authzValue = Request.Headers.Get("Authorization");
if (string.IsNullOrEmpty(authzValue) || !authzValue.StartsWith("Basic ", StringComparison.OrdinalIgnoreCase))
{
return null;
}
var token = authzValue.Substring("Basic ".Length).Trim();
return await token.TryGetPrincipalFromBasicCredentialsUsing(Options.ValidateCredentials);
}
protected override Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode == 401)
{
Response.Headers.Append("WWW-Authenticate", "Basic realm=" + Options.Realm);
}
return Task.FromResult<object>(null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment