3

I have a WebApi app that is using Windows Azure Active Directory Bearer Authentication to authenticate users. After the user is authenticated, I want to query Azure's Graph Api to get more information about the user.

I have a solution that works, but seems very hacky. I read the Authorization header and strip out the bearer part, and then I use AquireToken to get the new token:

var authHeader = HttpContext.Current.Request.Headers["Authorization"];
var tokenMatch = Regex.Match(authHeader, @"(?<=^\s*bearer\s+).+$", RegexOptions.IgnoreCase);

var result = authInfo.AuthContext.AcquireToken(resourceId, authInfo.Credential, 
    new UserAssertion(tokenMatch.Value));

return result.AccessToken;

There has to be a better way, but I've tried AcquireToken many different overloads and this was the only way I could get it to work. I tried AcquireTokenSilent, which works in my client app because there is a token in the TokenCache, but when I try in the WebApi, there doesn't seem anywhere to implement a TokenCache.

Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70

1 Answers1

7

That is indeed somewhat hacky :-) see https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet for a way in which you can retrieve the incoming token through the ClaimsPrincipal. It boils down to passing TokenValidationParameters = new TokenValidationParameters{ SaveSigninToken = true } in the options and retrieving in from your controller or filter code via

var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext; 
vibronet
  • 7,364
  • 2
  • 19
  • 21
  • Thanks, this is exactly what I was missing. http://stackoverflow.com/questions/14083885/bootstrapcontext-is-null-on-claimsidentity/33827070#33827070 – Jaanus Nov 20 '15 at 12:45