Acquiring an Access token by using JWT used for AzureBearerAuthentication

我与影子孤独终老i 提交于 2019-12-20 04:45:11

问题


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.


回答1:


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; 


来源:https://stackoverflow.com/questions/32083079/acquiring-an-access-token-by-using-jwt-used-for-azurebearerauthentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!