用于创建服务主体的 Azure 函数

标签 azure azure-active-directory azure-functions azure-container-registry

创建 Azure 函数来创建 AAD 服务主体的推荐方法是什么。

我们是否应该使用 Powershell 来执行 Azure 函数?

最佳答案

根据您的评论至Create User来自 Azure function使用 client_credentials 授予流程在这里,我为您提供了 azure 函数的确切示例。即插即用:))

示例包含:

  1. 如何使用 client_credentials 获取 token 流量
  2. Azure Active Directory上创建用户租户Azure函数

访问 token 类:

public   class AccessTokenClass
    {
        public string token_type { get; set; }
        public string expires_in { get; set; }
        public string resource { get; set; }
        public string scope { get; set; }
        public string access_token { get; set; }

    }

Azure Active Directory 创建用户类:

public class AzureFunctionCreateUserClass
    {
        public bool accountEnabled { get; set; }
        public string displayName { get; set; }
        public string mailNickname { get; set; }
        public string userPrincipalName { get; set; }
        public PasswordProfile passwordProfile { get; set; }
    }

Azure Active Directory 用户密码配置文件类:

 public class PasswordProfile
    {
        public bool forceChangePasswordNextSignIn { get; set; }
        public string password { get; set; }
    }

添加引用:

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Collections.Generic;
using System.Net.Http.Headers;

Azure 函数体:

[FunctionName("FunctionCreateUserUsingRestAPI")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
    try
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        //Read Request Body
        var content = await new StreamReader(req.Body).ReadToEndAsync();

        //Extract Request Body and Parse To Class
        AzureFunctionCreateUserClass objFuncRequestClass = JsonConvert.DeserializeObject<AzureFunctionCreateUserClass>(content);

       // Variable For Validation message return
        dynamic validationMessage;


        // Validate param  I am checking here. For Testing I am not taking from here But you can
        if (string.IsNullOrEmpty(objFuncRequestClass.displayName))
        {
            validationMessage = new OkObjectResult("displayName is required!");
            return (IActionResult)validationMessage;
        }
        if (string.IsNullOrEmpty(objFuncRequestClass.mailNickname))
        {
            validationMessage = new OkObjectResult("mailNicknameis required!");
            return (IActionResult)validationMessage;
        }

        if (string.IsNullOrEmpty(objFuncRequestClass.userPrincipalName))
        {
            validationMessage = new OkObjectResult("userPrincipalName is required Format: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ecb99f899ea28d8189acb583999eb889828d8298c2838281858f9e839f838a98c28f8381" rel="noreferrer noopener nofollow">[email protected]</a>!");
            return (IActionResult)validationMessage;
        }

        //Token Request Endpoint
        string tokenUrl = $"https://login.microsoftonline.com/YourTenant.onmicrosoft.com/oauth2/token";
        var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

        tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            ["grant_type"] = "client_credentials",
            ["client_id"] = "b603c7be-a866-Your_client_id-e6921e61f925",
            ["client_secret"] = "Vxf1SluKbgu4PF0N-client_Secret-SeZ8wL/Yp8ns4sc=",
            ["resource"] = "https://graph.microsoft.com"
        });

        dynamic json;
        AccessTokenClass results = new AccessTokenClass();
        HttpClient client = new HttpClient();
        //Request For Token
        var tokenResponse = await client.SendAsync(tokenRequest);

        json = await tokenResponse.Content.ReadAsStringAsync();
        //Extract Token Into class
        results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
        var accessToken = results.access_token;

        //Azure Ad Password profile object
        PasswordProfile objPass = new PasswordProfile();
        objPass.forceChangePasswordNextSignIn = true;
        objPass.password = "yourNewUserPass";

        //Azure AD user Object
        AzureFunctionCreateUserClass objCreateUser = new AzureFunctionCreateUserClass();
        objCreateUser.accountEnabled = true;
        objCreateUser.displayName = "KironFromFucntion";
        objCreateUser.mailNickname = "KironMailFromFunction";
        objCreateUser.userPrincipalName = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54012731261a353931140d3b212600313a353a207a3b3a393d37263b273b32207a373b39" rel="noreferrer noopener nofollow">[email protected]</a>";
        objCreateUser.passwordProfile = objPass;


        //Convert class object to JSON
        var jsonObj = JsonConvert.SerializeObject(objCreateUser);
        var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");


        using (HttpClient clientNew = new HttpClient())
        {

            var postJsonContent = new StringContent(jsonObj, Encoding.UTF8, "application/json");

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //Post Rquest To Create User Rest Endpoint URL: https://graph.microsoft.com/v1.0/users
            var rsponseFromApi= await client.PostAsync("https://graph.microsoft.com/v1.0/users", postJsonContent);

            //Check Reqeust Is Successfull
            if (rsponseFromApi.IsSuccessStatusCode)
            {
                var result_string = await responseFromApi.Content.ReadAsStringAsync();
                dynamic responseResults = JsonConvert.DeserializeObject<dynamic>(result_string);

                return new OkObjectResult(responseResults);

            }
            else
            {
                var result_string = await rsponseFromApi.Content.ReadAsStringAsync();
                return new OkObjectResult(result_string);
            }
        }

    }
    catch (Exception ex)
    {

        return new OkObjectResult(ex.Message);
    }

}

请求格式:

{
  "accountEnabled": true,
  "displayName": "displayName-value",
  "mailNickname": "mailNickname-value",
  "userPrincipalName": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f481849ad98295988191b480919a959a80d98295988191da9b9a999d97869b879b9280da979b99" rel="noreferrer noopener nofollow">[email protected]</a>",
  "passwordProfile" : {
    "forceChangePasswordNextSignIn": true,
    "password": "password-value"
  }
}

在 Azure 门户上检查新创建的用户:

只是为了确保检查您新创建的用户 Azure Portal All Users 。请参阅下面的屏幕截图:

enter image description here

要记住的一点:

对于 Azure Active Directory Create users 访问确保您具有以下权限:

  1. User.ReadWrite.All
  2. 权限类型:Application

您可以查看here 。请参阅屏幕截图以更好地理解:确保您已单击 Grant admin consent for yourTenant添加权限后。

![enter image description here

注意:您可以这样做Create UserAzure Active Directory将 Azure Function 与 Client_Credentials 一起使用 token 有效地流向特定 API 端点。

关于用于创建服务主体的 Azure 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56564434/

相关文章:

azure - 向 Azure 容器实例入口点提供参数

java - 对涉及 azure ad b2c 的安全 REST API 进行基于角色的访问

c# - 在 Azure Function 中按顺序处理服务总线消息(无并发调用)

Azure AD Multi-Tenancy 登录 - 使用 microsoftonline.com 和 microsoftonline.de 中的租户

Azure AD B2C - 支持守护程序应用程序以及 B2C 客户端(例如网页和 native 移动应用程序)

azure - Azure Functions 与 App Insights 中的错误报告

azure - 具有二进制 Azure 函数的 DocumentDb

powershell - 使用 Azure 资源管理器时如何获取 CustomScriptExtensions 的输出?

azure - 微软图形API : Accessing presences information via an Application scope

asp.net - 将多个容器上载到Azure容器注册表