【发布时间】:2020-09-24 09:19:32
【问题描述】:
我正在开发一个小 WPF 应用程序,它应该从 MS Graph API 查询一些数据。我想使用 SSO,所以用户不必单独登录应用程序。
该应用在已加入 Azure AD 的设备上运行。用户是 AADC 同步 AD 用户。 AAD 租户与 ADFS 联合。用户使用 Hello for Business (PIN) 或密码进行身份验证。产生的问题是一样的。
我可以确认用户通过以下方式获得了 PRT:
dsregcmd /status
AzureAdPrt: YES
以防万一:Azure AD 中的应用注册设置为“将应用程序视为公共客户端”。并且配置了以下重定向 URI:
- https://login.microsoftonline.com/common/oauth2/nativeclient
- https://login.live.com/oauth20_desktop.srf
- msalxxxxxxx(appId)://auth
- urn:ietf:wg:oauth:2.0:oob
根据我找到的示例,我正在使用以下代码尝试获取访问令牌。但是GetAccountsAsync() 方法不会返回任何用户,也不会抛出任何错误或异常。
谁能告诉我,我在这里缺少什么?
任何帮助将不胜感激!
PS:当我尝试使用“交互式身份验证”时,它工作正常。
public GraphAuthProvider(string appId, string tenantId, string[] scopes)
{
_scopes = scopes;
try
{
_msalClient = PublicClientApplicationBuilder
.Create(appId)
.WithAuthority(AadAuthorityAudience.AzureAdMyOrg, true)
.WithTenantId(tenantId)
.Build();
}
catch (Exception exception)
{
_log.Error(exception.Message);
_log.Error(exception.StackTrace);
throw;
}
}
public async Task<string> GetAccessToken()
{
_log.Info("Starting 'GetAccessToken'...");
var accounts = await _msalClient.GetAccountsAsync();
_userAccount = accounts.FirstOrDefault();
// If there is no saved user account, the user must sign-in
if (_userAccount == null)
{
_log.Info("No cached accounts found. Trying integrated authentication...");
[...]
}
else
{
// If there is an account, call AcquireTokenSilent
// By doing this, MSAL will refresh the token automatically if
// it is expired. Otherwise it returns the cached token.
var userAccountJson = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(_userAccount));
_log.Info($"Found cached accounts. _userAccount is: {userAccountJson}");
var result = await _msalClient
.AcquireTokenSilent(_scopes, _userAccount)
.ExecuteAsync();
return result.AccessToken;
}
}
【问题讨论】:
标签: c# azure-active-directory single-sign-on azure-ad-graph-api msal