使用图形API在Azure活动目录中以编程方式注册应用 [英] Programmatically register app in azure active directory using graph api
问题描述
我正在尝试使用图形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.
推荐答案
更好的方法是使用我说这是一种更好的方法,因为当您使用客户端库时,您会获得很多好处,例如无需处理原始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).
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.
我在类似的 查看全文