首页 > 解决方案 > 从 MVC 5(Azure AD) 访问 WebAPI 时,此请求的授权被拒绝

问题描述

因此,当我从 Azure AD 获取访问令牌时,我试图从 MVC 5 调用 WebAPI ToDoList,并且发送的令牌如下所示:request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", appToken)。但无论授权结果如何:- StatusCode : 401,改写:授权已被拒绝。但是,尽管在 NativeClientApp、.NET Core 中使用相同的授权,但我关注了 microsoft azure 文章和论坛,但没有成功。

请注意:WebAPI 项目和 MVC 项目在同一个解决方案中。

  public async Task<string> GetTokenForApplication()
    {
        string signedInUserID = 
    ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        string tenantID = 
    ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = 
    ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

// Get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential clientcred = new ClientCredential(clientId, appKey);
        // Initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
        AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
        return appToken = authenticationResult.AccessToken;
    }




public async Task<ActionResult> Index()
    {
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
      //  
        try
        {
            Uri servicePointUri = new Uri(graphResourceID);
            Uri serviceRoot = new Uri(servicePointUri, tenantID);
            appToken = string.Empty;
            ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
                  async () => await GetTokenForApplication());

            // Use the token for querying the graph to get the user details

            var result = await activeDirectoryClient.Users
                .Where(u => u.ObjectId.Equals(userObjectID))
                .ExecuteAsync();
            IUser user = result.CurrentPage.ToList().First();

            List<TodoItem> itemList = new List<TodoItem>();
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, todoListBaseAddress + "api/todolist");
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", appToken);
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
                JsonSerializerSettings settings = new JsonSerializerSettings();
                String responseString = await response.Content.ReadAsStringAsync();
                responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings);
                foreach (Dictionary<String, String> responseElement in responseElements)
                {
                    TodoItem newItem = new TodoItem();
                    newItem.Title = responseElement["Title"];
                    newItem.Owner = responseElement["Owner"];
                    itemList.Add(newItem);
                }

                return View();
            }

            return View(user);
        }
        catch (AdalException ex)
        {
            ex.ToString();
            // Return to error page.
            return View("Error");
        }
        // If the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
        catch (Exception ex)
        {
            ex.ToString();
            return View("Relogin");
        }
    }

标签: azureasp.net-mvc-5azure-active-directoryauthorizationwebapi

解决方案


推荐阅读