Skip to content

Instantly share code, notes, and snippets.

@steeleprice
Forked from pmhsfelix/gist:6148160
Created August 7, 2013 22:29
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 steeleprice/6179463 to your computer and use it in GitHub Desktop.
Save steeleprice/6179463 to your computer and use it in GitHub Desktop.
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