Azure函数创建服务主体

时间:2019-06-12 14:21:50

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

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

也许应该使用Powershell来执行Azure功能吗?

1 个答案:

答案 0 :(得分:1)

根据您的评论,使用client_credentialsCreate UserAzure function,授予流程在这里,我为您提供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;

天蓝色功能主体:

[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上的新创建用户。请参见以下屏幕截图:

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 User令牌流令牌将Azure Function有效地用于特定API端点的Azure Active Directory Client_Credentials