【问题标题】:AcquireTokenByUsernamePassword throws System.AggregateException and MsalServiceExceptionAcquireTokenByUsernamePassword 抛出 System.AggregateException 和 MsalServiceException
【发布时间】:2021-07-29 23:01:22
【问题描述】:

AcquireTokenByUsernamePassword 抛出 System.AggregateException 和 MsalServiceException:

第一个例外:

System.AggregateException: '发生一个或多个错误。 (联邦 服务于 https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID] 返回错误:身份验证失败)'

第二个例外:

MsalServiceException:联合服务位于 https://autologon.microsoftazuread-sso.com/domain.com/winauth/trust/2005/usernamemixed?client-request-id=[ID] 返回错误:身份验证失败

string clientId = "client-id";
string tenant = "tenant-id";
    
// Open connection
string authority = "https://login.microsoftonline.com/" + tenant;
string[] scopes = new string[] { "user.read" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
                          .WithAuthority(authority)
                          .Build();
var securePassword = new SecureString();
foreach (char c in user.Password.ToCharArray())  // you should fetch the password
securePassword.AppendChar(c);  // keystroke by keystroke
var results = app.AcquireTokenByUsernamePassword(scopes, user.UserName, securePassword).ExecuteAsync().Result.IdToken;

【问题讨论】:

  • 您检查过您的密码吗?对吗?
  • 您能否检查一下您是否启用了“允许公共客户端流”?
  • @JimXu 允许公共客户端流已启用
  • @Tassisto 您是否为您的用户帐户启用了 mfa?
  • @JimXu 我在哪里可以启用此功能?

标签: .net-core azure-active-directory jwt token bearer-token


【解决方案1】:

您的scope 设置不正确。我认为您想调用您的自定义 api 而不是 ms graph api,因此您应该为您的公开 api 获取一个令牌。你在代码中设置的scope是ms graph api的权限,而不是你自定义的api范围。

因此,您需要将scope 设置为:api://{api app client id}/.default

【讨论】:

  • .default 是什么?
  • @Tassisto /.default 范围是一种静默请求的方式。见官方文档的解释:docs.microsoft.com/en-us/azure/active-directory/develop/…
  • 它说:“然后代码返回一个 id_token,而不是访问令牌。”不是需要使用访问令牌而不是 id 令牌来访问 API 吗?
  • @Tassisto 当然,您必须使用访问令牌。
猜你喜欢
  • 2020-08-20
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多