使用用于 AzureBearerAuthentication 的 JWT 获取访问令牌 [英] Acquiring an Access token by using JWT used for AzureBearerAuthentication

查看:13
本文介绍了使用用于 AzureBearerAuthentication 的 JWT 获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 WebApi 应用程序,它使用 Windows Azure Active Directory 承载身份验证对用户进行身份验证.用户通过身份验证后,我想查询 Azure 的 Graph Api 以获取有关用户的更多信息.

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.

我有一个可行的解决方案,但看起来很老套.我阅读了 Authorization 标头并去掉了承载部分,然后我使用 AquireToken 来获取新的令牌:

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*bearers+).+$", RegexOptions.IgnoreCase);

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

return result.AccessToken;

必须有更好的方法,但我已经尝试了许多不同的 AcquireToken 重载,这是我可以让它工作的唯一方法.我尝试了 AcquireTokenSilent,它可以在我的客户端应用程序中使用,因为 TokenCache 中有一个令牌,但是当我在 WebApi 中尝试时,似乎没有任何地方可以实现 TokenCache.

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.

推荐答案

这确实有点 hacky :-) 请参阅 https://github.com/AzureADSamples/WebAPI-OnBehalfOf-DotNet 了解可以通过 ClaimsPrincipal 检索传入令牌的方法.它归结为在选项中传递 TokenValidationParameters = new TokenValidationParameters{ SaveSigninToken = true } 并通过

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; 

这篇关于使用用于 AzureBearerAuthentication 的 JWT 获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆