2015-12-21 44 views
2

爱Azure的AD B2C ...期待,当它超出预览!如何提交Azure的AD B2C新用户提交的MVC应用程序

有我需要帮助,把我的头周围的一个特例。

我有一个页面,我通过网络的形式捕捉新的电子邮件地址。

并称邮件给我的邮件列表后,我想,然后不给用户点击任何其他按钮用我的ASP.NET MVC网站自动创建一个AD帐户B2C。

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

我看到它可以添加使用图形API的新用户。 但是,这个例子是使用cmd程序编写的。

有谁知道是否有一些示例代码,让我插入一个用户到AD B2C的MVC控制器内?

回答

3

继承人我如何做到这一点从ASP.Net MVC一些示例代码。记住你需要包括ClientId和Clientsecret(它们与ASP.Net webapp分开),正如你提到的文章中所解释的那样。从控制器代码 - 助手类:

UserController中:

// 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("https://stackoverflow.com/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(); 
    } 

最后,从模型的一些samplecode,请注意JsonProperty(顺序:

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"; 
相关问题