未经授权在Microsoft Graph Api中无法获取数据

时间:2018-12-10 07:48:23

标签: c# asp.net azure-ad-graph-api microsoft-planner

我目前正在开发一个ASP.NET MVC 5站点,该站点使用Microsoft Graph API应用程序检索数据并将数据插入Microsoft Planner。该站点已经具有Azure Active Directory身份验证。我目前正在使用以下代码获取访问令牌以登录Graph API应用程序。

    public async Task<ActionResult> SignIn()
    {
        AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/common");
        string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);
        Uri authUri = await authContext.GetAuthorizationRequestUrlAsync("https://graph.microsoft.com/", SettingsHelper.ClientId,
                                                              new Uri(redirectUri), UserIdentifier.AnyUser, null);

        // Redirect the browser to the Azure signin page
        return Redirect(authUri.ToString());
    }

    public async Task<ActionResult> Authorize()
    {
        // Get the 'code' parameter from the Azure redirect
        string authCode = Request.Params["code"];

        // The same url we specified in the auth code request
        string redirectUri = Url.Action("Authorize", "Planner", null, Request.Url.Scheme);

        // Use client ID and secret to establish app identity
        ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);

        TokenCache fileTokenCache = new FilesBasedAdalV3TokenCache("C:\\temp\\justin.bin");
        AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthorityTenantID, fileTokenCache);
        AuthenticationResult authResult = null;
        try
        {
            // Get the token silently first
            authResult = await authContext.AcquireTokenAsync(SettingsHelper.O365UnifiedResource, credential);
        }
        catch (AdalException ex)
        {
            authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, fileTokenCache);

            authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            authCode, new Uri(redirectUri), credential, SettingsHelper.O365UnifiedResource);

            return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
        }
        finally
        {
            // Save the token in the session
            Session["access_token"] = authResult.AccessToken;
        }

        return Redirect(Url.Action("Index", "Planner", null, Request.Url.Scheme));
    }

上面的代码获取访问令牌没有任何问题。我能够毫无问题地获取活动目录的所有用户并将其存储在数据库中。但是,当我尝试获取与任务有关的任何数据时,我会不断遇到以下错误

{  
   StatusCode:401,
   ReasonPhrase:'Unauthorized',
   Version:1.1,
   Content:System.Net.Http.StreamContent,
   Headers:{  
      Transfer-Encoding:      chunked request-id:40      b53d20-c4fc-4614-837b-57a6bebb8d79 client-request-id:40      b53d20-c4fc-4614-837b-57a6bebb8d79 x-ms-ags-diagnostic:{  
         "ServerInfo":{  
            "DataCenter":"North Europe",
            "Slice":"SliceC",
            "Ring":"2",
            "ScaleUnit":"000",
            "Host":"AGSFE_IN_17",
            "ADSiteName":"NEU"
         }
      }      Duration:28.4537      Strict-Transport-Security:      max-age=31536000 Cache-Control:      private Date:Fri,
      07      Dec 2018 14:12:50      GMT Content-Type:application/json
   }
}

我已经检查过azure应用,它具有完全访问权限。任何帮助,将不胜感激

1 个答案:

答案 0 :(得分:1)

我设法解决了我的问题。问题是Graph Api要求您以委派帐户运行,以及将App设置为Azure本地应用程序。

使用的代码如下

        private async Task<string> GetAccessToken(string resourceId, string userName, string password)
            {
                try
                    {
                        var authority = ConfigurationManager.AppSettings["ida:AuthorizationLoginUri"] + ConfigurationManager.AppSettings["ida:TenantId"];
                        var authContext = new AuthenticationContext(authority);
                        var credentials = new UserPasswordCredential(userName, password);
                        var authResult = await authContext.AcquireTokenAsync(resourceId, ConfigurationManager.AppSettings["ida:ClientIdNativeClient"], credentials);
                        // Get the result
                        return authResult.AccessToken;
                    }
                catch (Exception ex)
                    {
                    // TODO: handle the exception
                    return;
                    }
            }

我发现这个网站https://karinebosch.wordpress.com/2017/12/18/microsoft-graph/与我遇到了相同的问题