我在 Azure AD 中注册了一个控制台应用程序,该应用程序连接到 CRM Online(使用 these steps 配置)。它查询 Web API。
应用程序需要在没有用户交互的情况下运行...但不幸的是,对 AcquireTokenSilentAsync
的调用始终失败,并且只有 AcquireTokenAsync
有效。这会出现一个用户登录对话框,无法满足用户交互要求!
有什么方法可以阻止此提示,可以通过将登录信息保存在客户端计算机上的某个位置(到目前为止还没有起作用),也可以使用证书(但你如何做到这一点?)还是其他什么?
我正在使用 ADAL for .NET v3.10.305110106 版本。以下代码用于验证:
private static async Task PerformOnlineAuthentication()
{
_authInfo = new AuthInfo(); // This is just a simple class of parameters
Console.Write("URL (include /api/data/v8.x): ");
var url = Console.ReadLine();
BaseUri = new Uri(url);
var absoluteUri = BaseUri.AbsoluteUri;
_authInfo.Resource = absoluteUri;
Console.Write("ClientId: ");
var clientId = Console.ReadLine();
_authInfo.ClientId = clientId;
Console.Write("RedirectUri: ");
var redirectUri = Console.ReadLine();
_authInfo.RedirectUri = new Uri(redirectUri);
var authResourceUrl = new Uri($"{_authInfo.Resource}/api/data/");
var authenticationParameters = await AuthenticationParameters.CreateFromResourceUrlAsync(authResourceUrl);
_authInfo.AuthorityUrl = authenticationParameters.Authority;
_authInfo.Resource = authenticationParameters.Resource;
_authInfo.Context = new AuthenticationContext(_authInfo.AuthorityUrl, false);
}
private static async Task RefreshAccessToken()
{
if (!IsCrmOnline())
return;
Console.WriteLine($"Acquiring token from: {_authInfo.Resource}");
AuthenticationResult authResult;
try
{
authResult = await _authInfo.Context.AcquireTokenSilentAsync(_authInfo.Resource, _authInfo.ClientId);
}
catch (AdalSilentTokenAcquisitionException astae)
{
Console.WriteLine(astae.Message);
authResult = await _authInfo.Context.AcquireTokenAsync(_authInfo.Resource, _authInfo.ClientId, _authInfo.RedirectUri, new PlatformParameters(PromptBehavior.RefreshSession));
}
HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
最佳答案
感谢@aravind谁指出了active-directory-dotnet-native-headless样本。
该示例包含 FileCache class它继承自 Microsoft.IdentityModel.Clients.ActiveDirectory.TokenCache
。该类管理将凭据缓存到磁盘上的加密文件。这意味着第一次运行时只有一个提示,之后凭据将存储在本地。
最后的拼图是:
调用不同的构造函数签名以使用 FileCache 初始化
AuthenticationContext
:_authInfo.Context = new AuthenticationContext( _authInfo.AuthorityUrl, false, new FileCache());
将用户的凭据获取到
Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential
对象(请参阅TextualPrompt()
method in the sample )将凭据传递给
AcquireTokenAsync()
的不同方法签名:authResult = await _authInfo.Context.AcquireTokenAsync( _authInfo.Resource, _authInfo.ClientId, userCredential);
关于azure - ADAL 身份验证无对话框提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37384660/