Skip to content

Instantly share code, notes, and snippets.

@BertCraven
Created March 27, 2011 23:22
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 BertCraven/889753 to your computer and use it in GitHub Desktop.
Save BertCraven/889753 to your computer and use it in GitHub Desktop.
namespace AzureClaimsAuthenticator
{
using System;
using System.Linq;
using System.Net;
using OpenRasta.Authentication;
public class AzureClaimsAuthenticationScheme : IAuthenticationScheme
{
private const string TrustedTokenIssuer = "https://[your_solution_namespace].accesscontrol.windows.net/";
private const string TrustedAudience = "[your_trusted_audience]";
private const string TrustedIssuerKey = "[your_issuer_key]";
private const string IdentityClaimType = "[your_identity_claim_type]";
#region IAuthenticationScheme Members
public AuthenticationResult Authenticate(OpenRasta.Web.IRequest request)
{
// get the authorization header
var authorizationHeader = request.Headers[HttpRequestHeader.Authorization.ToString()];
// check the header format
if (string.IsNullOrEmpty(authorizationHeader))
{
return new AuthenticationResult.Failed();
}
// the correct format for the token is
// WRAP access_token="TokenGoesHere"
// the only part we want is the TokenGoesHere part
if (!authorizationHeader.StartsWith("WRAP "))
{
return new AuthenticationResult.MalformedCredentials();
}
var nameValuePair = authorizationHeader.Substring("WRAP ".Length).Split(new[] { '=' }, 2);
if (nameValuePair.Length != 2 || nameValuePair[0] != "access_token" || !nameValuePair[1].StartsWith("\"") || !nameValuePair[1].EndsWith("\""))
{
return new AuthenticationResult.MalformedCredentials();
}
var token = nameValuePair[1].Trim('"');
// validate the token
var validator = new TokenValidator(TrustedTokenIssuer, TrustedAudience, Convert.FromBase64String(TrustedIssuerKey));
if (!validator.Validate(token))
{
return new AuthenticationResult.Failed();
}
// check for an action claim and get the value
var claims = validator.GetNameValues(token);
var identity = claims[IdentityClaimType];
if (identity == null)
{
return new AuthenticationResult.MalformedCredentials();
}
var roles = (from claim in claims from part in claim.Value.Split(',') select string.Format("{0}:{1}", claim.Key, part)).ToArray();
return new AuthenticationResult.Success(identity, roles);
}
public void Challenge(OpenRasta.Web.IResponse response)
{
response.StatusCode = 401;
response.Headers.Add("WWW-Authenticate", string.Format("{0} realm=\"{1}\"", this.Name, TrustedAudience));
}
public string Name
{
get { return "WRAP"; }
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment