使用图形 api 以编程方式在 azure 活动目录中注册应用程序

Programmatically register app in azure active directory using graph api(使用图形 api 以编程方式在 azure 活动目录中注册应用程序)
本文介绍了使用图形 api 以编程方式在 azure 活动目录中注册应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I am trying to register an application in Azure AD using graph API, I have a method CallRestAPI which will make the request. Below is the code

    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;
    }

我认为我在正文中发送参数的方式不正确,任何人都可以指导我如何使这段代码工作,或者有更好的方法来实现同样的效果吗?谢谢你.

I think the way I am sending parameters in the body is not correct can anyone guide me how to make this code work or is there a better way to achieve the same? Thank you.

推荐答案

实现相同的更好方法,即使用 Azure AD 注册应用程序将使用 Azure AD Graph 客户端库

A better way to achieve the same i.e. register an app with Azure AD will be to make use of Azure AD Graph Client Library

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

I say it's a better approach because when you use the client library you reap multiple benefits like no raw HTTP request handling, writing more convenient and declarative C# code, depending on a well tested library, async support etc.

我想使用的底层 Graph API 仍然是一样的

Underlying Graph API used will still be the same I suppose

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

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

Here is sample code (C#) to create an Azure AD application

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

Notice that I've kept app.PublicClient flag as true to register as a native application. You can set it to false if you want to register it as a web application.

        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 来创建应用程序.使用应用程序权限不是强制性的,您也可以通过提示用户输入凭据来使用委派权限.查看更详细示例的链接(旧示例但仍然有用).

Setup: I have an application registered in Azure AD, which has required permissions as application permission - Read and Write all applications and grant permissions is done for this app. Now using this application's client id and client secret, a token is acquired and Azure AD Graph API is called to create an application. It is not mandatory to use application permissions, you can also use delegated permissions by prompting user for credentials. See links to more detailed examples (old ones but still useful).

  • 使用 Graph 客户端库的控制台应用程序

Web 应用使用 Graph 客户端库调用 Graph

Azure AD Graph 客户端库 2.0 公告页面

附带说明,您可以使用较新的 Microsoft Graph API 也一样,

On a side note, you could do this using the newer Microsoft Graph API as well,

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

但创建应用程序的能力仍处于测试阶段,因此不推荐用于生产工作负载.因此,即使 Microsoft Graph API 会被推荐用于大多数场景,至少对于这个场景,使用 Azure AD Graph API 是当前的方式.

but the ability to create applications is still in beta and hence not recommeded for production workloads. So even though Microsoft Graph API would be recommende for most scenarios, at least for this one, using Azure AD Graph API is the way to go currently.

我在类似的 在这里发帖.

这篇关于使用图形 api 以编程方式在 azure 活动目录中注册应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)