如何使用 Microsoft Graph 更改用户密码 API

How to change a user password using Microsoft Graph API

我正在编写一种 passwd 命令行应用程序来更改 Azure 帐户的密码。像这样工作的东西:

> passwd someuser Passw*rd1

阅读所有文档后,我在 Azure 门户中创建了我的应用程序,并获得了所有需要的权限,我即将获得应用程序授权,就在获得访问令牌之前。

问题不是获取授权码,而是 https://login.microsoftonline.com/<tenantName>/oauth2/v2.0/authorize returns 对我来说是一个 HTML 页面。

据我了解,此页面应该为登录用户提供委派所需权限的机会,但这是管理员用户使用的命令。事实上,此时没有登录用户。

我错过了什么?

你在哪里调用 /authorize 端点?

您可以在浏览器中这样调用并使用您的帐户登录:

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&state=12345

然后你会在地址栏中得到一个"code"。 使用此代码请求访问令牌:

POST /{tenant}/oauth2/v2.0/token HTTP/1.1

client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&grant_type=authorization_code
&client_secret=JqQX2PNo9bpM0uEihUPzyrh

查看来自 Request an authorization code and Request an access token 的详细信息。

有一个关于重置用户密码的代码示例。

$tennantid        = ''         
$SubscriptionId   = ''         
$ApplicationID    = ''         
$ApplicationKey   = ''
$TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $tennantid 
$ARMResource = "https://graph.microsoft.com";

$Body = @{
        'resource'= $ARMResource
        'client_id' = $ApplicationID
        'grant_type' = 'client_credentials'
        'client_secret' = $ApplicationKey
        'scope' = 'https%3A%2F%2Fgraph.microsoft.com%2FDirectory.AccessAsUser.All'
}

$params = @{
    ContentType = 'application/x-www-form-urlencoded'
    Headers = @{'accept'='application/json'}
    Body = $Body
    Method = 'Post'
    URI = $TokenEndpoint
}

$token = Invoke-RestMethod @params

$headers = @{}
$headers.Add("authorization","Bearer $($Token.access_token)")
$ResetPwd = @{
    "passwordProfile" = @{
        "forceChangePasswordNextSignIn" = "false"
        "password" = "Test123456!"
    }
} | ConvertTo-Json
Invoke-RestMethod -Headers $headers -Method Patch -Uri "https://graph.microsoft.com/beta/users/$($respons.id)" -ContentType "application/json" -Body $ResetPwd

然后使用这个和上面的代码工作。

$servicePrincipal = Get-MsolServicePrincipal -ServicePrincipalName ServicePrincipalName
$roleId = (Get-MsolRole -RoleName "Company Administrator").ObjectId
Add-MsolRoleMember -RoleObjectId $roleId -RoleMemberObjectId $servicePrincipal.ObjectId -RoleMemberType servicePrincipal

希望对您有所帮助。