Azure – 如何使用Microsoft Graph API更新Azure AD B2C中用户的密码配置文件?

huangapple go评论71阅读模式
英文:

Azure - How to update the password profile of a user in Azure AD B2C using the Microsoft Graph API?

问题

我正在尝试使用Microsoft Graph API提供的更新端点更改Azure AD B2C中用户的密码。

我在实施时遵循了Microsoft的文档:https://learn.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&tabs=http#http-request

以下是我使用的代码:

static async Task Main(string[] args)
{
    string tenantId = "tenant-id";
    string clientId = "client-id";
    string clientSecret = "client-secret";
    var objectId = "object-id";
    var newPassword = "newPassword";

    try
    {
        string accessToken = await GetAccessToken(tenantId, clientId, clientSecret);

        await ResetPassword(accessToken, objectId, newPassword);

        Console.WriteLine("Password reset successfully!");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }

}

static async Task<string> GetAccessToken(string tenantId, string clientId, string clientSecret)
{
    using (HttpClient client = new HttpClient())
    {
        string tokenEndpoint = $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token";
        var body = $"grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}&scope=https://graph.microsoft.com/.default";

        var response = await client.PostAsync(tokenEndpoint, new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"));
        var responseBody = await response.Content.ReadAsStringAsync();

        var tokenJson = System.Text.Json.JsonDocument.Parse(responseBody).RootElement;
        string accessToken = tokenJson.GetProperty("access_token").GetString();

        return accessToken;
    }
}

static async Task ResetPassword(string accessToken, string objectId, string newPassword)
{
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken}");

        string graphApiEndpoint = $"https://graph.microsoft.com/v1.0/users/{objectId}";

        var body = new
        {
            passwordProfile = new
            {
                forceChangePasswordNextSignIn = false,
                password = newPassword
            }
        };

        var jsonBody = System.Text.Json.JsonSerializer.Serialize(body);
        var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

        var response = await httpClient.PatchAsync(graphApiEndpoint, content);
        var responseBody = await response.Content.ReadAsStringAsync();
        response.EnsureSuccessStatusCode();

    }
}

但是,尽管我为租户获取了访问令牌,并使用该访问令牌调用了Graph API中的更新端点,但返回了403错误(权限不足以完成操作)。

我在Azure AD B2C中为此控制台应用程序创建了一个应用程序,并添加了以下权限:

  • Directory.AccessAsUser.All(委托)
  • Directory.ReadWrite.All(应用程序)
  • User.ReadWrite.All(应用程序)

我该如何使其工作?

英文:

I am trying to change the password of a user in Azure AD B2C using the update endpoint provided by the Microsoft Graph API.

I followed this Microsoft documentation when I implemented this -
https://learn.microsoft.com/en-us/graph/api/user-update?view=graph-rest-1.0&amp;tabs=http#http-request

Following is the code I used,

static async Task Main(string[] args)
    {
        string tenantId = &quot;tenant-id&quot;;
        string clientId = &quot;client-id&quot;;
        string clientSecret = &quot;client-secret&quot;;
        var objectId = &quot;object-id&quot;;
        var newPassword = &quot;newPassword&quot;;

        try
        {
            string accessToken = await GetAccessToken(tenantId, clientId, clientSecret);

            await ResetPassword(accessToken, objectId, newPassword);

            Console.WriteLine(&quot;Password reset successfully!&quot;);
        }
        catch (Exception ex)
        {
            Console.WriteLine($&quot;An error occurred: {ex.Message}&quot;);
        }

    }

    static async Task&lt;string&gt; GetAccessToken(string tenantId, string clientId, string clientSecret)
    {
        using (HttpClient client = new HttpClient())
        {
            string tokenEndpoint = $&quot;https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token&quot;;
            var body = $&quot;grant_type=client_credentials&amp;client_id={clientId}&amp;client_secret={clientSecret}&amp;scope=https://graph.microsoft.com/.default&quot;;

            var response = await client.PostAsync(tokenEndpoint, new StringContent(body, Encoding.UTF8, &quot;application/x-www-form-urlencoded&quot;));
            var responseBody = await response.Content.ReadAsStringAsync();

            var tokenJson = System.Text.Json.JsonDocument.Parse(responseBody).RootElement;
            string accessToken = tokenJson.GetProperty(&quot;access_token&quot;).GetString();

            return accessToken;
        }
    }

    static async Task ResetPassword(string accessToken, string objectId, string newPassword)
    {
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, $&quot;Bearer {accessToken}&quot;);

            string graphApiEndpoint = $&quot;https://graph.microsoft.com/v1.0/users/{objectId}&quot;;

            var body = new
            {
                passwordProfile = new
                {
                    forceChangePasswordNextSignIn = false,
                    password = newPassword
                }
            };

            var jsonBody = System.Text.Json.JsonSerializer.Serialize(body);
            var content = new StringContent(jsonBody, Encoding.UTF8, &quot;application/json&quot;);

            var response = await httpClient.PatchAsync(graphApiEndpoint, content);
            var responseBody = await response.Content.ReadAsStringAsync();
            response.EnsureSuccessStatusCode();

        }
    }

The access token was obtained for the tenant and using this access token the update endpoint in Graph API was called but a 403 error (Insufficient privileges to complete the operation) was returned.

I created an application for this console app in the Azure AD B2C and added the following permissions,
Directory.AccessAsUser.All (Delegated), Directory.ReadWrite.All (Application), User.ReadWrite.All (Application)

How can I make this work?

答案1

得分: 1

在仅应用程序访问中,调用应用程序必须具有“User.ReadWrite.All”应用程序权限,并且必须至少具有“User Administrator”Azure AD内置角色。

资源:

Azure AD内置角色

更新用户 - 检查passwordProfile属性的注释

英文:

In application-only access, the calling app must have the User.ReadWrite.All application permission and must have at least the User Administrator Azure AD built-in role.

Resources:

Azure AD built-in roles

Update user - check comment for passwordProfile property

答案2

得分: 1

Add a User Administrator role assignment for the App registration of the application created.
添加一个用户管理员角色分配给创建的应用程序的应用注册。

英文:

Add a User Administrator role assignment for the App registration of the application created

答案3

得分: 1

确保您已将“用户管理员”或“全局管理员”角色分配给应用程序。

导航至Azure门户 > Azure AD > 角色和管理员 > 用户管理员 > 点击添加分配 > 选择应用程序 > 点击添加按钮。

注意:这将需要10-15分钟才能生效。

英文:

Make sure you have assigned "User Administrator" or "Global Administrator" role to the application

Navigate to Azure Portal > Azure AD > Roles and Administrators> User Administrator > Click on Add Assignments > select the application > click on Add button.

Note: This will take 10-15 minutes to take effect.

huangapple
  • 本文由 发表于 2023年5月15日 15:03:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76251594.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定