.NET Core 2.2中调用AcquireTokenAsync时为502.3

时间:2018-12-04 14:46:28

标签: c# .net-core microsoft-graph

我遇到问题了。我正在使用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和提供者位于Core库中,如下所示:

Screenshot of architecture

2 个答案:

答案 0 :(得分:1)

因此,事实证明,将软件包Microsoft.IdentityModel.Clients.ActiveDirectory从v3.19.8升级到v4.4.1时出现了问题。出于某种原因,v3.19.8之上的版本均无法与我的代码一起使用,导致在我尝试调用https://graph.microsoft.com时崩溃,但是我降级后,问题立即消失了。

答案 1 :(得分:-1)

尝试使用AcquireToken代替AcquireTokenAsync

azureAuthenticationContext.AcquireToken