Skip to content

Instantly share code, notes, and snippets.

@caleb-vear
Created September 28, 2012 05:07
Show Gist options
  • Save caleb-vear/3798027 to your computer and use it in GitHub Desktop.
Save caleb-vear/3798027 to your computer and use it in GitHub Desktop.
An example of adding an OAuth message handler to authenticate web api requests.
using System.ServiceModel.Channels;
using System.ServiceModel.Web;
using Microsoft.IdentityModel.Tokens;
namespace System.Net.Http
{
using Threading;
using Web;
using Web.Http;
using Microsoft.IdentityModel.Claims;
using Microsoft.IdentityModel.Configuration;
using Microsoft.IdentityModel.Swt;
/// <summary>
/// Authenticates the ongoing request using Windows Identity Foundation and
/// SimpleWebToken (wif.swf). Grabs the token from the header and performs the authentication.
/// </summary>
public class OAuthAuthenticationHandler : MessageProcessingHandler
{
ServiceConfiguration _serviceConfiguration;
public ServiceConfiguration ServiceConfiguration
{
get
{
if (_serviceConfiguration == null)
_serviceConfiguration = new ServiceConfiguration();
if (!_serviceConfiguration.IsInitialized)
_serviceConfiguration.Initialize();
return _serviceConfiguration;
}
}
protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var token = ExtractTokenFromHeader(request);
if (token != null)
{
var identities = ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token);
var principal = ClaimsPrincipal.CreateFromIdentities(identities);
request.SetUserPrincipal(principal);
Thread.CurrentPrincipal = principal;
HttpContext.Current.User = principal;
}
}
catch (InvalidSecurityTokenException)
{
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
return request;
}
protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)
{
return response;
}
static SimpleWebToken ExtractTokenFromHeader(HttpRequestMessage request)
{
var authorizationHeader = request.Headers.Authorization;
if (authorizationHeader != null && authorizationHeader.Scheme == "OAuth")
return new SimpleWebToken(authorizationHeader.Parameter);
return null;
}
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new OAuthAuthenticationHandler());
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment