使用图形API

时间:2019-02-06 14:10:57

标签: c# azure-active-directory microsoft-graph azure-ad-graph-api

我正在尝试使用图形API在Azure AD中注册应用程序,我有一个方法CallRestAPI将发出请求。 下面是代码

    public async Task<Response> AzureADApp()
    {
        Response responseMessage = new Response();
        try
        {
            var token = GenerateToken();
            List<(string, string)> listHeaders = new List<(string, string)>();
            listHeaders.Add(("Authorization", string.Concat("Bearer" + " " + token)));
            listHeaders.Add(("Content-Type", "application/json"));

            List<(string, string)> param = new List<(string, string)>();
            param.Add(("displayName", "VS1Application123"));
            param.Add(("homepage", "https://localhost:44358/"));
            param.Add(("identifierUris", "https://G7CRM4L/6958490c-21ae-4885-804c-f03b3add87ad"));

            string callUrl = "https://graph.windows.net/G7CRM4L/applications/?api-version=1.6";
            var result = CallRestAPI(callUrl, "", Method.POST, listHeaders, param);

        }
        catch (Exception ex)
        {
            responseMessage.StatusCode = Convert.ToInt16(HttpStatusCode.InternalServerError);
        }
        return responseMessage;
    }

    public async Task<IRestResponse> CallRestAPI(string BaseAddress, string SubAddress, Method method, List<(string, string)> headersList = null, List<(string, string)> paramsList = null)
    {
        var call = new RestClient(BaseAddress + SubAddress);
        var request = new RestRequest(method);

        if (headersList != null)
        {
            foreach (var header in headersList)
            {
                request.AddHeader(header.Item1, header.Item2);
            }
        }
        if (paramsList != null)
        {
            foreach (var param in paramsList)
            {
                request.AddParameter(param.Item1, param.Item2);
            }
        }

        var response = call.ExecuteTaskAsync(request);

        return response.Result;
    }

我认为我在体内发送参数的方式不正确,有人可以指导我如何使此代码正常工作,还是有更好的方法实现这一目标? 谢谢。

1 个答案:

答案 0 :(得分:1)

达到相同目的(即在Azure AD中注册应用)的更好方法是利用Azure AD Graph Client Library

我说这是一种更好的方法,因为当您使用客户端库时,您会获得很多好处,例如无需处理原始HTTP请求,编写更方便和声明性的C#代码(取决于经过良好测试的库,异步支持等)。

使用的底层图形API仍与我想的一样

POST https://graph.windows.net/{tenant-id}/applications?api-version=1.6

以下是创建Azure AD应用程序的示例代码(C#)

请注意,我将app.PublicClient标志保留为true,以注册为本机应用程序。如果要将其注册为Web应用程序,可以将其设置为false。

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using Microsoft.Azure.ActiveDirectory.GraphClient;
        using Microsoft.IdentityModel.Clients.ActiveDirectory;

        namespace CreateAzureADApplication
        {
            class Program
            {
                static void Main(string[] args)
                {

                    ActiveDirectoryClient directoryClient;

                    ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri("https://graph.windows.net/{yourAADGUID}"),
            async () => await GetTokenForApplication());


                    Application app = new Application();
                    app.DisplayName = "My Azure AD Native App";
                    app.PublicClient = true;
                    app.Homepage = "https://myazureadnativeapp";
                    activeDirectoryClient.Applications.AddApplicationAsync(app).GetAwaiter().GetResult();

                 }

             public static async Task<string> GetTokenForApplication()
             {
                   AuthenticationContext authenticationContext = new AuthenticationContext(
                "https://login.microsoftonline.com/{yourAADGUID}",
                false);

            // Configuration for OAuth client credentials 

                ClientCredential clientCred = new ClientCredential("yourappclientId",
                    "yourappclientsecret"
                    );
                AuthenticationResult authenticationResult =
                    await authenticationContext.AcquireTokenAsync("https://graph.windows.net", clientCred);

                return authenticationResult.AccessToken;

            }
          }
        }

设置:我在Azure AD中注册了一个应用程序,该应用程序具有所需的权限作为应用程序权限-读取和写入所有应用程序,并为此应用程序完成了授予权限。现在,使用此应用程序的客户端ID和客户端密钥,将获取一个令牌,并调用Azure AD Graph API创建一个应用程序。使用应用程序权限不是强制性的,您也可以通过提示用户输入凭据来使用委派权限。请参阅指向更详细示例的链接(旧示例,但仍然有用)。

另一方面,您也可以使用较新的Microsoft Graph API

    POST https://graph.microsoft.com/beta/applications

,但是创建应用程序的功能仍处于测试阶段,因此不建议将其用于生产工作负载。因此,即使在大多数情况下都推荐使用Microsoft Graph API,至少在这种情况下,使用Azure AD Graph API是当前的方式。

我在此处类似的SO Post中对此进行了详细介绍。

相关问题