【问题标题】:Azure function to create Service Principal [closed]用于创建服务主体的 Azure 函数 [关闭]
【发布时间】:2019-06-12 14:21:50
【问题描述】:

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

我们是否应该使用 Powershell 来执行 Azure 功能?

【问题讨论】:

  • 没听懂问题。能否请您详细说明一下要求?
  • 如何使用 Azure 函数在 azure AAD 中创建用户/服务主体
  • 为什么要使用 Azure 函数?可以使用 poweshell 或 cli 创建服务主体
  • 您可以使用 REST API 从`Azure Function` 创建用户。但是对于服务原则,除了Update and Other operation possible,没有要创建的 API。我可以帮助您使用 Azure Function 创建用户

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


【解决方案1】:

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

示例包含:

  1. 您将如何使用client_credentials 流获取令牌
  2. Azure Active Directory 租户 Azure 函数上创建用户

访问令牌类:

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: UserName@YourTenant.onmicrosoft.com!");
            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 = "UserName@YourTenant.onmicrosoft.com";
        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": "upn-value@tenant-value.onmicrosoft.com",
  "passwordProfile" : {
    "forceChangePasswordNextSignIn": true,
    "password": "password-value"
  }
}

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

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

要记住的要点:

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

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

您可以查看here。查看屏幕截图以获得更好的理解:确保您在添加权限后点击了Grant admin consent for yourTenant

注意:这就是您如何在Azure Active Directory 上使用带有Client_Credentials 令牌的Azure 函数将令牌有效地流向特定API 端点的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多