我刚刚开始使用 Azure AD (Microsoft Entra ID),所以这看起来像是一个菜鸟问题。
我有一个 Dot Net Core 7.0 Web API 应用程序,它公开了用于用户登录的 REST API。 我在 Azure AD 中有多个活动用户帐户,我想使用此 API 登录 AD。
为此,我使用 Nuget 包 Microsoft.IdentityModel.Clients.ActiveDirectory,版本 5.3.0。
这是我的登录代码:
string clientId = Configuration.GetSection("ClientId").Value;
string domain = Configuration.GetSection("TokenEndpoint").Value;
string[] scopes = { "User.ReadWrite.All" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId).WithAuthority(domain).Build();
try
{
var result = await app.AcquireTokenByUsernamePassword(scopes, userData.email, userData.Password).ExecuteAsync();
return result;
}
catch (MsalException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
if(ex.InnerException != null){
Console.WriteLine(ex.InnerException.Message);
Console.WriteLine(ex.InnerException.StackTrace);
}
throw ex;
}
此代码正在重新调整以下错误:
{
"error":"invalid_grant",
"error_description":"AADSTS65001: The user or administrator has not consented to use the application with ID '******' named '******'. Send an interactive authorization request for this user and resource. Trace ID: ****** Correlation ID: ****** Timestamp: 2024-02-12 08:34:04Z",
"error_codes":[
65001
],
"timestamp":"2024-02-12 08:34:04Z",
"trace_id":"******",
"correlation_id":"******",
"suberror":"consent_required"
}
我在线检查了以下资源:
根据这些资源中提出的建议,我做了以下更改
您能否提供有关此错误的任何线索?
请注意,Microsoft.IdentityModel.Clients.ActiveDirectory库调用目前已已弃用且不再受支持的 Azure AD Graph API,如果使用,会引发
错误。invalid_grant
或者,您可以使用 Microsoft.Identity.Client 包来生成调用 Microsoft Graph API 的访问令牌。
就我而言,我注册了一个 Entra ID 应用程序并授予了 Delegate 类型的 User.ReadWrite.All 权限,如下所示:
为了通过用户名密码流程生成访问令牌,我运行了下面的示例 c# 代码安装
Microsoft.Identity.Client
包:
using Microsoft.Identity.Client;
namespace Sri
{
class Program
{
static async Task Main(string[] args)
{
string clientId = "appId";
string domain = "https://login.microsoftonline.com/tenantId/oauth2/v2.0/authorize";
string[] scopes = { "User.ReadWrite.All" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId).WithAuthority(domain).Build();
try
{
UserData userData = new UserData { email = "[email protected]", Password = "xxxxxxxxx" };
var result = await app.AcquireTokenByUsernamePassword(scopes, userData.email, userData.Password).ExecuteAsync();
Console.WriteLine("Token acquired successfully.");
Console.WriteLine($"Access Token: {result.AccessToken}");
}
catch (MsalException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
if (ex.InnerException != null)
{
Console.WriteLine(ex.InnerException.Message);
Console.WriteLine(ex.InnerException.StackTrace);
}
throw ex;
}
}
}
public class UserData
{
public string email { get; set; }
public string Password { get; set; }
}
}
回复:
为了确认这一点,您可以通过将其粘贴到 jwt.ms 网站来解码,并检查
aud
和 scp
声明是否具有 valid 值:
现在,您可以使用此令牌调用 Microsoft Graph API 请求,例如列出、创建、更新和删除 Azure AD 用户。