2

大爱 Azure AD B2C……期待它何时结束预览!!!

有一个特殊情况,我需要帮助解决我的问题。

我有一个页面,我可以在其中通过 Web 表单捕获新的电子邮件地址。

将该电子邮件添加到我的邮件列表后,我想自动创建一个 AD B2C 帐户,而无需让用户使用我的 ASP.NET MVC 站点单击任何其他按钮。

在阅读文章时:https ://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/

我看到可以使用 Graph API 添加新用户。但是,此示例是使用 cmd 程序编写的。

有谁知道是否有一些示例代码允许我将用户插入到 MVC 控制器内的 AD B2C 中?

4

1 回答 1

3

下面是一些关于我如何从 ASP.Net MVC 执行此操作的示例代码。请记住,您需要包含 ClientId 和 Clientsecret(它们与 ASP.Net webapp 分开),如您提到的文章中所述。来自控制器的代码--helperclass:

用户控制器:

  // POST: User/Create
    [HttpPost]
    public async Task<ActionResult> Create(b2cuser usr)
    {
        try
        {
            usr.AlternativeSignInNamesInfo.First().Value = string.Format("{0}_{1}", usr.FirstName, usr.LastName);
            usr.DisplayName = string.Format("{0} {1}", usr.FirstName, usr.LastName);

            string json = Newtonsoft.Json.JsonConvert.SerializeObject(usr, Formatting.None);
            Utils.GraphAPIHelper api = new Utils.GraphAPIHelper(graphAPIClientId, graphAPIClientSecret, tenant);
            string res = await api.GraphPostRequest("/users/", json);
            return RedirectToAction("Index");
        }
        catch (Exception e)
        {
            return View();
        }
    }

在 GraphAPIHelper 中:

    internal async Task<string> GraphPostRequest(string api, string json)
    {
        AuthenticationResult result = authContext.AcquireToken(graphResourceID, credential);
        HttpClient http = new HttpClient();
        string url = aadGraphEndpoint + tenant + api + "?" + aadGraphVersion;

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
        request.Content = new StringContent(json, Encoding.UTF8, "application/json");
        HttpResponseMessage response = await http.SendAsync(request);

        if (!response.IsSuccessStatusCode)
        {
            string error = await response.Content.ReadAsStringAsync();
            object formatted = JsonConvert.DeserializeObject(error);
            throw new WebException("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
        }

        return await response.Content.ReadAsStringAsync();
    }

最后,来自模型的一些示例代码,请注意 JsonProperty(Order:

public class b2cuser
{
    [JsonProperty(Order = 0, PropertyName = "accountEnabled")]
    public bool AccountEnabled = true;

    [JsonProperty(Order = 1, PropertyName = "alternativeSignInNamesInfo")]
    public List<AlternativeSignInNamesInfo> AlternativeSignInNamesInfo { get; set; }

    [JsonProperty(Order = 2, PropertyName = "creationType")]
    public string CreationType = "NameCoexistence";
于 2016-03-02T09:59:37.460 回答