azure - 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
解决方案
您提供的代码似乎使用 ADAL 而不是 MSAL。
主要区别在于ADAL
您将使用 anAuthenticationContext
来获取令牌,而在MSAL
您使用ConfidentialClientApplication
orPublicClientApplication
时,这取决于应用程序是在后端运行还是在用户设备上运行。
这是关于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());
推荐阅读
- kernel-extension - 端点安全 - 阻止用户以写入模式打开文件
- c - 信号处理程序在线程中不起作用
- wpf - 将 Datagrid 分成 2 部分
- jmeter - JMeter 脚本 - 不下载 png、jpg、woff
- c++ - c ++重新初始化静态常量成员
- reactjs - 安装 react-router-dom 时出错 npm install 问题
- python - 如何在for循环范围python中使用多个变量
- c# - Microsoft CRM 365 将文件上传到商机
- xml - 用于从 url 下载 xml 的 ps 脚本 - 每个输出文件都是唯一的
- javascript - 如何将具有多个部分的表单数据转换为 json