首页 > 解决方案 > ADFS:以编程方式获取令牌

问题描述

因此,我们构建了一组受 ADFS (MSAL) 保护的 Azure 函数

我们已经在 ADFS 中配置了一个应用程序,并让它在我们的 Android 客户端上运行良好。

我们现在想做一些 API 测试,所以我们想以编程方式生成 Auth 令牌来测试 API 的

我根本无法使用以下代码,也许我的租户 ID 错误,在应用程序配置中,它是一个 GUID (42b03d0b-d7f2-403e-b764-0dbdcf0505f6),但示例说它是我们的域

string userName = "-";
string password = "-";
string clientId = "ee13c922-bf4b-4f0a-ba39-ea74e1203c6e";
var credentials = new UserPasswordCredential(userName, password);
var authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/acostaonline.onmicrosoft.com");
var result = await authenticationContext.AcquireTokenAsync("https://graph.windows.net", clientId, credentials);

更新

因此将代码更改为 MSAL 并仍然尝试通过用户名和密码登录。现在它只是超时

string authority = "https://login.microsoftonline.com/42b03d0b-d7f2-403e-b764-0dbdcf0505f6/";
string[] scopes = new string[] { "user.read" };
PublicClientApplication app = new PublicClientApplication("ee13c922-bf4b-4f0a-ba39-ea74e1203c6e", authority);
var accounts = await app.GetAccountsAsync();

Microsoft.Identity.Client.AuthenticationResult result = null;
      if (accounts.Any())
      {
         result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault());
      }
      else
      {
          try
          {
             var securePassword = new SecureString();
             foreach (char c in "PASSWORD")        // you should fetch the password keystroke
                securePassword.AppendChar(c);  // by keystroke

             result = await app.AcquireTokenByUsernamePasswordAsync(scopes, "AUSER@acosta.com",
                                                                           securePassword);
          }
     }

错误

SocketException:连接尝试失败,因为连接方一段时间后没有正确响应,或者连接建立失败,因为连接的主机没有响应 172.26.200.77:443

标签: azureadfsmsal

解决方案


您提供的代码似乎使用 ADAL 而不是 MSAL。

主要区别在于ADAL您将使用 anAuthenticationContext来获取令牌,而在MSAL您使用ConfidentialClientApplicationorPublicClientApplication时,这取决于应用程序是在后端运行还是在用户设备上运行。

这是关于ADAL.NET 和 MSAL.NET 应用程序之间的差异的文章。

当您使用 MSAL.Net 获取 Microsoft Graph API 的令牌时,您可以使用以下代码:

public static PublicClientApplication PublicClientApp = new 
PublicClientApplication(ClientId);
var app = App.PublicClientApp;
ResultText.Text = string.Empty;
TokenInfoText.Text = string.Empty;
var accounts = await app.GetAccountsAsync();
authResult = await app.AcquireTokenSilentAsync(_scopes, accounts.FirstOrDefault());

更多详情可以参考这篇文章,左侧菜单中还包括AndroidiOS


推荐阅读