正在使用Azure AD B2C...期待它何时退出预览版!
有个特殊的情况我需要你帮我打理一下。
我有一个页面,我通过网页形式捕获新的电子邮件地址。
在将该电子邮件添加到我的邮件列表后,我希望自动创建一个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?
发布于 2016-03-02 09:59:37
下面是一些示例代码,说明我是如何在ASP.Net MVC中这样做的。请记住,您需要包括ClientId和Clientsecret (它们独立于ASP.Net the应用程序),正如您提到的文章中所解释的那样。控制器中的代码--helperclass:
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("/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(顺序:
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";
https://stackoverflow.com/questions/34397149
复制