【问题标题】:How do you use AcquireTokenSilentAsync to authenticate a user?如何使用 AcquireTokenSilentAsync 对用户进行身份验证?
【发布时间】:2019-05-02 17:07:03
【问题描述】:

我正在尝试从加入 Azure AD 的计算机以编程方式授权 Azure 应用程序。

如果我在 Internet Explorer 中访问应用程序 URL,它能够验证已登录的用户帐户。

我当前的代码如下所示:

使用 Microsoft.IdentityModel.Clients.ActiveDirectory; AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/TENANTGUID"); Uri uri = new Uri("urn:ietf:wg:oauth:2.0:oob"); var pparams = new PlatformParameters(PromptBehavior.Auto, null); AuthenticationResult 结果 = await context.AcquireTokenAsync("https://graph.windows.net", "1950a258-227b-4e31-a9cf-717495945fc2", uri, pparams);

此调用成功,但我想为当前登录的用户获取令牌。

AcquireTokenAsync 调用的前两个参数是resourceclientid

我可以获得我想要访问的应用程序的主页 url 和应用程序 ID,但找不到两者的组合。

我应该向该函数传递哪些参数以静默验证登录用户并获取可用于后续调用应用程序的授权标头?

【问题讨论】:

  • 你想要像https://login.microsoftonline.com/$TenantID/oauth2/token这样的东西
  • 资源是您想要令牌的 APO 的标识符。 https://graph.windows.net 是 Azure AD Graph API 的标识符。 https://graph.microsoft.com 是 Microsoft Graph API 的标识符。这一切都取决于令牌缓存中是否包含一些凭据。
  • 如果我改为使用 oauth2/token,我会收到错误 AADSTS90002: Tenant token not found。如果租户没有活动订阅,则可能会发生这种情况。请咨询您的订阅管理员。
  • 如果我尝试使用应用程序 clientid 代替 graph.windows.net,我会收到如下错误:AADSTS50011:请求中指定的回复 url 与为应用程序配置的回复 url 不匹配:'客户ID'。 AADSTS50001:在名为 TENANTGUID 的租户中找不到名为 CLIENTNAME 的应用程序

标签: c# azure adal msal


【解决方案1】:

我现在建议您使用 MSAL.NET Integrated Windows Authentication 加入域或 AAD 的机器:

代码类似于:

static async Task GetATokenForGraph()
{
 string tenant = "contoso.com" // can also be a GUID or organizations for multi-tenant
 string authority = $"https://login.microsoftonline.com/{tenant}";
 string[] scopes = new string[] { "user.read" };
 PublicClientApplication app = new PublicClientApplication(clientId, authority);
 var accounts = await app.GetAccountsAsync();

 AuthenticationResult result=null;
 if (accounts.Any())
 {
 result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault());
 }
 else
 {
  try
  {
   result = await app.AcquireTokenByIntegratedWindowsAuthAsync(scopes);
  }
  catch (MsalUiRequiredException ex)
   { 
    // For details see the article 

【讨论】:

  • 感谢您的帮助 当我尝试上述方法时,首先找不到帐户,然后 AcquireTokenByIntegratedWindowsAuthAsync 失败并出现错误 Win32Exception:系统无法联系域控制器来为身份验证请求提供服务。请稍后再试
  • If I try using AcquireTokenAsync instead of AcquireTokenByIntegratedAuthAsync a sign-in windows pops up with the logged on user Id in it but when that Id is selected the following error occurs: AADSTS50011: The reply url specified in the请求与为应用程序配置的回复 url 不匹配:'CLIENTID'。
  • @保罗海豚。如果系统无法联系到域控制器,这可能是因为您的计算机未加入域,或者您的 VPN 已关闭
  • 对于 AcquireTokenAsync,这意味着您需要在应用注册中检查 urn:ietf:wg:oauth:2.0:oob 回复 URI。请看github.com/Azure-Samples/…
猜你喜欢
  • 1970-01-01
  • 2021-07-26
  • 2013-01-19
  • 2018-12-08
  • 2012-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多