使用 Azure AD,如何使用临时密码发送更改密码请求?

With Azure AD, How can I send a change password request with a temporary password?

我有一个关于 Azure AD 和图形的具体问题 API。

我正在向 API 发出简单的更改密码请求。这适用于用户能够登录的情况。但是,如果用户通过门户将其密码重置为临时密码,则他们下次登录时需要更改密码。我遇到的问题是在尝试为该用户获取身份验证令牌时返回异常:

AADSTS50055: Force Change Password.

因此,如果我无法获得身份验证令牌,我应该如何使用 Graph API 发送更改密码请求,以便我的用户可以在我的应用程序中更改他们的密码?

下面是我为已经可以登录的用户更改密码的代码:

public SendPasswordChangeRequest(string userId, string newPass, string oldPass) {
    try {
        HttpClient http = new HttpClient();
        string action = string.Format("/users/{0}/changePassword", user.DistinguishedName);
        string url = string.Format("https://graph.windows.net/{0}{1}?api-version=1.6", tenantId, action);
        object bodyObject = new { currentPassword = oldPass, newPassword = newPass }; 
        string body = JsonConvert.SerializeObject(bodyObject);

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
        request.Content = new StringContent(body, Encoding.UTF8, "application/json");

        AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantName));
        UserPasswordCredential credential = new UserPasswordCredential(userId, oldPass); //userId and oldPass are parameters passed in

        AuthenticationResult authResult = authContext.AcquireTokenAsync("https://graph.windows.net/", clientId, credential).Result;
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);

        HttpResponseMessage httpResponse = http.SendAsync(request).Result;
    }
    catch (Exception ex) {
        //authResult throws the error into here
        //Error returned from Azure AD:
        //AADSTS50055: Force Change Password.
    }
}

简短的回答是:你不能。

这是一个很好的例子,说明了为什么在您可以使用任何交互式身份验证流程的任何情况下都不鼓励使用 username/password 流程。来自 OAuth 2.0 spec,这是此模式调用的内容(添加了重点):

The resource owner password credentials (i.e., username and password) can be used directly as an authorization grant to obtain an access token. The credentials should only be used when there is a high degree of trust between the resource owner and the client (e.g., the client is part of the device operating system or a highly privileged application), and when other authorization grant types are not available (such as an authorization code).

如果您的应用程序是本机客户端应用程序(即富客户端应用程序),您应该调用其中一个 AcquireToken 流程,该流程会弹出带有 Azure AD 托管登录的登录提示页。这将为用户提供更改密码的机会(并允许其他中断,例如多重身份验证)。

对于其他场景(Web 应用、单页应用等),Authentication Scenarios for Azure AD has additional details, and samples and additional reference can be found in the Azure Active Directory developer's guide