使用 Graph API,使用 http post 请求在 Azure Active Directory (B2C) 中创建新用户

2023-11-22

我之前一直使用 Active Directory 身份验证库 (ADAL) 以编程方式添加用户,但现在我需要定义“signInNames”(= 用户电子邮件),而 ADAL 似乎无法实现这一点(如果我错了,请告诉我) 。

现在我尝试使用 HTTP POST 以编程方式添加新用户(本地帐户),如下MSDN 上的文档.

//Get access token (using ADAL)
var authenticationContext = new AuthenticationContext(AuthString, false);
var clientCred = new ClientCredential(ClientId, ClientSecret);
var authenticationResult = authenticationContext.AcquireTokenAsync(ResourceUrl, clientCred);
var token = authenticationResult.Result.AccessToken;


//HTTP POST CODE
const string mail = "[email protected]";
// Create a new user object.
var user = new CustomUser
{
    accountEnabled = true,
    country = "MS",
    creationType = "LocalAccount",
    displayName = mail,
    passwordPolicies = "DisablePasswordExpiration,DisableStrongPassword",
    passwordProfile = new passwordProfile { password = "jVPmEm)6Bh", forceChangePasswordNextLogin = true },
    signInNames = new signInNames { type = "emailAddress", value = mail }
};

var url = "https://graph.windows.net/" + TenantId + "/users?api-version=1.6";

var jsonObject = JsonConvert.SerializeObject(user);

using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

    var response = client.PostAsync(url,
        new StringContent(JsonConvert.SerializeObject(user).ToString(),
            Encoding.UTF8, "application/json"))
            .Result;

    if (response.IsSuccessStatusCode)
    {
        dynamic content = JsonConvert.DeserializeObject(
            response.Content.ReadAsStringAsync()
            .Result);

        // Access variables from the returned JSON object
        var appHref = content.links.applications.href;
    }
}

但我没有成功,得到这样的回应:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content:....}

有什么想法我应该做什么吗?我成功使用 Powershell 脚本,但我需要在我的 C# 应用程序中执行此操作。


感谢您的回复 飞雪,我相信我有正确的权限。我做了什么来解决我的问题。

首先,我删除了自己的自定义类“NewUser”,然后我下载了这个示例项目:https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet/blob/master/B2CGraphClient/B2CGraphClient.cs消除我的代码错误的风险。我修改了它来支持我的需求,然后创建了一个简单的 JObject:

var jsonObject = new JObject
                        {
                            {"accountEnabled", true},
                            {"country", customer.CustomerBase.Company},
                            {"creationType", "LocalAccount"},
                            {"displayName", pendingCustomer.Email.Trim()},
                            {"passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword"},
                            {"passwordProfile", new JObject
                            {
                                {"password", pwd},
                                {"forceChangePasswordNextLogin", true}
                            } },
                            {"signInNames", new JArray
                                {
                                    new JObject
                                    {
                                        {"value", pendingCustomer.Email.Trim()},
                                        {"type", "emailAddress"}
                                    }
                                }
                            }
                        };

client = new B2CGraphClient(ClientId, ClientSecret, TenantId);
var response = await client.CreateUser(jsonObject.ToString());
var newUser = JsonConvert.DeserializeObject<User>(response);

来自 B2CGraphClient.cs

        private async Task<string> SendGraphPostRequest(string api, string json)
    {
        // NOTE: This client uses ADAL v2, not ADAL v4
        var result = authContext.AcquireToken(Globals.aadGraphResourceId, credential);
        var http = new HttpClient();
        var url = Globals.aadGraphEndpoint + tenant + api + "?" + Globals.aadGraphVersion;

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

        if (!response.IsSuccessStatusCode)
        {
            var error = await response.Content.ReadAsStringAsync();
            var formatted = JsonConvert.DeserializeObject(error);
            //Console.WriteLine("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
            Logger.Error("Error Calling the Graph API: \n" + JsonConvert.SerializeObject(formatted, Formatting.Indented));
        }
        Logger.Info((int)response.StatusCode + ": " + response.ReasonPhrase);

        return await response.Content.ReadAsStringAsync();
    }

这最终解决了我所有的问题,这可能是我的 NewCustomer 类序列化中的格式错误,然后被 API 拒绝。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Graph API,使用 http post 请求在 Azure Active Directory (B2C) 中创建新用户 的相关文章

  • 无法使用 strptime() 获取秒数

    我收到 YYYY MM DDThh mm ss S Z hh mm 这种格式的日期时间 我正在尝试使用复制该值strptime如下所示 struct tm time 0 char pEnd strptime datetime Y m dT
  • ROWNUM 的 OracleType 是什么

    我试图参数化所有现有的 sql 但以下代码给了我一个问题 command CommandText String Format SELECT FROM 0 WHERE ROWNUM lt maxRecords command CommandT
  • 属性对象什么时候创建?

    由于属性实际上只是附加到程序集的元数据 这是否意味着属性对象仅根据请求创建 例如当您调用 GetCustomAttributes 时 或者它们是在创建对象时创建的 或者 前两个的组合 在由于 CLR 的属性扫描而创建对象时创建 从 CLR
  • 在 Xamarin Android 中将图像从 URL 异步加载到 ImageView 中

    我有一个包含多个项目的 ListView 列表中的每个项目都应该有一个与之关联的图像 我创建了一个数组适配器来保存每个列表项并具有我希望加载的图像的 url 我正在尝试使用 Web 请求异步加载图像 并设置图像并在加载后在视图中更新它 但视
  • fgets() 和 Ctrl+D,三次才能结束?

    I don t understand why I need press Ctrl D for three times to send the EOF In addition if I press Enter then it only too
  • SSH 主机密钥指纹与模式 C# WinSCP 不匹配

    我尝试通过 WinSCP 使用 C 连接到 FTPS 服务器 但收到此错误 SSH 主机密钥指纹 与模式不匹配 经过大量研究 我相信这与密钥的长度有关 当使用 服务器和协议信息 下的界面进行连接时 我从 WinSCP 获得的密钥是xx xx
  • 如何在 WPF RichTextBox 中跟踪 TextPointer?

    我正在尝试了解 WPF RichTextBox 中的 TextPointer 类 我希望能够跟踪它们 以便我可以将信息与文本中的区域相关联 我目前正在使用一个非常简单的示例来尝试弄清楚发生了什么 在 PreviewKeyDown 事件中 我
  • 如何针对 Nancy 中的 Active Directory 进行身份验证?

    这是一篇过时的文章 但是http msdn microsoft com en us library ff650308 aspx paght000026 step3 http msdn microsoft com en us library
  • 按字典顺序对整数数组进行排序 C++

    我想按字典顺序对一个大整数数组 例如 100 万个元素 进行排序 Example input 100 21 22 99 1 927 sorted 1 100 21 22 927 99 我用最简单的方法做到了 将所有数字转换为字符串 非常昂贵
  • 如何在 Team Foundation 上强制发表有意义的签入评论?

    我有一个开发团队有一个坏习惯 他们写道poor签入评论 当我们必须在团队基础上查看文件的历史记录时 这使得它成为一场噩梦 我已经启用了变更集评论政策 这样他们甚至可以在签到时留下评论 否则他们不会 我们就团队的工作质量进行了一些讨论 他们很
  • 初始化变量的不同方式

    在 C 中初始化变量有多种方法 int z 3 与 int 相同z 3 Is int z z 3 same as int z z 3 您可以使用 int z z 3 Or just int z 3 Or int z 3 Or int z i
  • 更改窗口的内容 (WPF)

    我创建了一个简单的 WPF 应用程序 它有两个 Windows 用户在第一个窗口中填写一些信息 然后单击 确定 这会将他们带到第二个窗口 这工作正常 但我试图将两个窗口合并到一个窗口中 这样只是内容发生了变化 我设法找到了这个更改窗口内容时
  • .NET 选项将视频文件流式传输为网络摄像头图像

    我有兴趣开发一个应用程序 它允许我从 xml 构建视频列表 包含视频标题 持续时间等 并将该列表作为我的网络摄像头流播放 这意味着 如果我要访问 ustream tv 或在实时通讯软件上激活我的网络摄像头 我的视频播放列表将注册为我的活动网
  • 用 C 实现 Unix shell:检查文件是否可执行

    我正在努力用 C 语言实现 Unix shell 目前正在处理相对路径的问题 特别是在输入命令时 现在 我每次都必须输入可执行文件的完整路径 而我宁愿简单地输入 ls 或 cat 我已经设法获取 PATH 环境变量 我的想法是在 字符处拆分
  • AccessViolationException 未处理

    我正在尝试使用史蒂夫 桑德森的博客文章 http blog stevensanderson com 2010 01 28 editing a variable length list aspnet mvc 2 style 为了在我的 ASP
  • EPPlus Excel 更改单元格颜色

    我正在尝试将给定单元格的颜色设置为另一个单元格的颜色 该单元格已在模板中着色 但worksheet Cells row col Style Fill BackgroundColor似乎没有get财产 是否可以做到这一点 或者我是否必须在互联
  • ListDictionary 类是否有通用替代方案?

    我正在查看一些示例代码 其中他们使用了ListDictionary对象来存储少量数据 大约 5 10 个对象左右 但这个数字可能会随着时间的推移而改变 我使用此类的唯一问题是 与我所做的其他所有事情不同 它不是通用的 这意味着 如果我在这里
  • Bing 地图运行时错误 Windows 8.1

    当我运行带有 Bing Map 集成的 Windows 8 1 应用程序时 出现以下错误 Windows UI Xaml Markup XamlParseException 类型的异常 发生在 DistanceApp exe 中 但未在用户
  • 如何在 C# 中播放在线资源中的 .mp3 文件?

    我的问题与此非常相似question https stackoverflow com questions 7556672 mp3 play from stream on c sharp 我有音乐网址 网址如http site com aud
  • 如何将字符串“07:35”(HH:MM) 转换为 TimeSpan

    我想知道是否有办法将 24 小时时间格式的字符串转换为 TimeSpan 现在我有一种 旧时尚风格 string stringTime 07 35 string values stringTime Split TimeSpan ts new

随机推荐