首页 文章

如何从SPA应用程序中的Web API访问Graph API

提问于
浏览
7

我有一个与WebAPI对话的Angular应用程序,用户通过Azure Active Directory进行身份验证

我在这里跟踪了示例https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi并且能够针对AD对用户进行身份验证并将其传递给Web API .

但是,我想访问Web API中的Graph API并获取当前用户配置文件信息 . 我该如何设置?

Updated to give more context on the setup:

我有一个网站(site.domain1.com),它承载制作SPA应用程序的html和javascript文件 . 我在api.domain2.com上托管了Web API . 使用OAAL隐式流与ADAL.js和angular-adal对Azure AD进行身份验证 . 我想在SPA中进行身份验证以获取API的accessToken . 我希望在API中作为查询Graph API的请求的一部分,以获取有关当前用户登录的更多信息 .

我能够获得API的accessToken,并且它当前生成了Claim Principal . 问题是使用Web API中的当前标识查询Graph API .

Update:

我不想将管理员权限授予Web API,但我更愿意将用户同意仅从浏览器转发到网站和Web api的“读取用户配置文件” .

我使用类似的方法来代表这里的样本https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof

它适用于我的测试AD并且不适用于 生产环境 AD的问题 . 说用户需要在使用Graph Api之前集中应用程序 . (对于 生产环境 AD我只有用户可以添加用户权限但不能添加应用程序权限 . 我的猜测是该方案工作我需要AD的全局管理员首先集中) . 最终,我最终将Web站点和Web API的Azure AD应用程序合并在一起,并使用与Bootstrap Tokens相同的On Behalf Of方法 . 但我想知道如何使它与2个应用程序正常工作 .

3 回答

  • 0

    权限可在Azure中的应用程序配置页面中进行配置,您可以选择要让应用程序访问的内容 .

    至于确认,您作为管理员可以选择 . 用户接受与您的应用共享数据或管理员确认租户下的所有数据 .

    这是正确的方法 . 我的前端和后端就是这样工作的 .

  • 0

    这应该让你开始

    How to use Microsoft Graph and Office 365 API in a Service or in a Windows App/UWP without a graphical interface

    https://blogs.msdn.microsoft.com/laurelle/2016/02/12/how-to-use-microsoft-graph-and-office-365-api-in-a-service-or-in-a-windows-appuwp-without-a-graphical-interface/

  • 0

    请参阅示例:https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web . 有一些代码可以访问Graph API并获取示例中的用户配置文件:

    ClientCredential credential = new ClientCredential(clientId, appKey);
    AuthenticationResult result = authContext.AcquireTokenSilent(graphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    
    // Call the Graph API manually and retrieve the user's profile.
    string requestUrl = String.Format(CultureInfo.InvariantCulture, graphUserUrl, HttpUtility.UrlEncode(tenantId));
    HttpClient client = new HttpClient();
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
    HttpResponseMessage response = await client.SendAsync(request);
    
    // Return the user's profile in the view.
    if (response.IsSuccessStatusCode) {
        string responseString = await response.Content.ReadAsStringAsync();
        profile = JsonConvert.DeserializeObject<UserProfile>(responseString);
    }
    

    您可以在此处查看更多信息:https://azure.microsoft.com/en-us/documentation/articles/active-directory-code-samples/#calling-azure-ad-graph-api

相关问题