Created
March 27, 2011 23:22
-
-
Save BertCraven/889753 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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