【发布时间】:2018-12-04 14:46:27
【问题描述】:
我遇到了问题。我正在使用 Microsoft Graph 通过OnBehalfOfMsGraphAuthenticationProvider.cs 获取当前登录的用户,如下面的solution 所示。
这一直完美无缺,但我一直在进行一些重构,突然在尝试执行我的 authContext.AcquireTokenAsync() 方法时出现错误。
HTTP Error 502.3 - Bad Gateway
有问题的代码如下所示:
public async Task AuthenticateRequestAsync(HttpRequestMessage request) {
var httpContext = _httpContextAccessor.HttpContext;
//Get the access token used to call this API
string token = await httpContext.GetTokenAsync("access_token");
//We are passing an *assertion* to Azure AD about the current user
//Here we specify that assertion's type, that is a JWT Bearer token
string assertionType = "urn:ietf:params:oauth:grant-type:jwt-bearer";
//User name is needed here only for ADAL, it is not passed to AAD
//ADAL uses it to find a token in the cache if available
var user = httpContext.User;
string userName =
user.FindFirst(ClaimTypes.Upn).Value ?? user.FindFirst(ClaimTypes.Email).Value;
var userAssertion = new UserAssertion(token, assertionType, userName);
//Construct the token cache
var cache = new DistributedTokenCache(user, _distributedCache,
_loggerFactory, _dataProtectionProvider);
var authContext = new AuthenticationContext(_configuration["AzureAd:Instance"] +
_configuration["AzureAd:TenantId"], true, cache);
var clientCredential = new ClientCredential(_configuration["AzureAd:ClientId"],
(string) _configuration["AzureAd:ClientSecret"]);
//Acquire access token
var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", clientCredential, userAssertion); //This is where it crashes
//Set the authentication header
request.Headers.Authorization = new AuthenticationHeaderValue(result.AccessTokenType, result.AccessToken);
}
我是通过我的OrdersController 调用它的:
// POST: api/Orders
[HttpPost]
public async Task<IActionResult> CreateAsync([FromBody] OrderDTO order) {
if (!ModelState.IsValid) {
return BadRequest(ModelState);
}
var graphUser = await this.graphApiService.GetUserProfileAsync();
重构包括将我的解决方案分为两个类库项目和一个 Web 项目——后者包含控制器和 React 应用程序。 GraphAPiClient 和提供程序位于核心库中,如下所示:
【问题讨论】:
-
可能这是身份验证问题stackoverflow.com/a/38754821/10634638
-
_configuration["AzureAd:Instance"] + _configuration["AzureAd:TenantId"]的输出是什么? -
@MarcLaFleur:我已经检查过了,输出是正确的。它们都与正确的 GUID 相对应(出于安全原因,我不想输入它们)。
-
@bestinamir 谢谢你的回答!这不是对login.microsoftonline.com 的调用,但是 - 当出现此问题时,我已经成功完成了该调用,现在我想使用我获得的令牌调用 Graph API。这以前有效 - 让我感到困惑的是我得到的奇怪错误。
-
权限不应该是两个 GUID,它应该是令牌颁发者的 URI。例如。
https://login.microsoftonline.com/{tenant-name}.onmicrosoft.com
标签: c# .net-core microsoft-graph-api