我正在开发 SPA/Web API 应用程序并使用 AAD B2C 进行用户身份验证。
作为一项功能,我想让用户从应用程序 UI 创建用户帐户,并且我计划使用 Microsoft Graph API 来实现此目的(POST /users)。
但是,我读到,要在此 API 上进行身份验证,我们必须使用客户端凭据工作流程(使用客户端密钥),但我发现这并不方便,因为 client_secret 将会过期。
您对如何改进 Microsoft Graph API 的使用流程有什么想法吗?
提前谢谢您
注意:如果您不想使用客户端密钥进行身份验证,那么您可以尝试使用基于证书的身份验证。
我创建了一个 Azure AD 应用程序并授予了应用程序权限:
使用 PowerShell 创建自签名证书:
$certname = "certname"
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256
Export-Certificate -Cert $cert -FilePath "C:/test/$certname.cer"
将证书导出到
.pfx
:
$mypwd = ConvertTo-SecureString -String "password" -Force -AsPlainText
Export-PfxCertificate -Cert $cert -FilePath "C:/test/$certname.pfx" -Password $mypwd
我在 Azure AD 应用程序中上传了
.cer
证书:
要创建Azure AD B2C用户,我使用了以下代码:
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Identity.Client;
using System.Security.Cryptography.X509Certificates;
X509Certificate2 certificate = new X509Certificate2("C:\\Users\\rukmini\\testrukkp.pfx", "xxxx");
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create("ClientAppID")
.WithCertificate(certificate)
.WithAuthority(new Uri("https://login.microsoftonline.com/TenantID"))
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult authResult = await confidentialClientApplication.AcquireTokenForClient(scopes).ExecuteAsync();
var user = new
{
accountEnabled = true,
displayName = "Adele Vance",
mailNickname = "AdeleV",
userPrincipalName = "[email protected]",
passwordProfile = new
{
forceChangePasswordNextSignIn = true,
password = "Password"
}
};
var json = JsonSerializer.Serialize(user);
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://graph.microsoft.com/v1.0/users", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("User created successfully.");
}
else
{
Console.WriteLine("Error creating user: " + await response.Content.ReadAsStringAsync());
}
用户创建成功如下:
否则,您可以创建具有自定义到期日期的客户端密钥: