我正在开发一个使用Azure AD进行身份验证的Angular 5前端的.net Core 2 Web应用程序。
我们的asp实现基于aspnetcore connect示例。 https://github.com/microsoftgraph/aspnetcore-connect-sample
我们在GraphAuthProvider.cs中有两个GetUserAccessTokenAsync方法的实现
我们可以获取应用程序的令牌,请参阅底部片段,但下面用于检索已登录用户的令牌的令牌正在抛出ServiceException。
显然cca变量中的用户数组不包含任何用户,但我们无法弄清楚原因。是否有任何在从Angular前端调用的web api后端使用Microsoft Graph的示例?
由于额外的服务器端处理,我们需要通过web-api进行调用,因此我们无法直接调用Graph。
代表登录用户获取图表访问令牌
public async Task<string> GetUserAccessTokenAsync(string userId)
{
_userTokenCache = new SessionTokenCache(userId, _memoryCache).GetCacheInstance();
var cca = new ConfidentialClientApplication(
_clientId,
_redirectUri,
_credential,
_userTokenCache,
null);
if (!cca.Users.Any()) throw new ServiceException(new Error
{
Code = "TokenNotFound",
Message = "User not found in token cache. Maybe the server was restarted."
});
try
{
var result = await cca.AcquireTokenSilentAsync(_scopes, cca.Users.First());
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
获取应用程序图形访问令牌
public async Task<string> GetClientAccessTokenAsync()
{
_appTokenCache = new SessionTokenCache(_clientId, _memoryCache).GetCacheInstance();
var cca = new ConfidentialClientApplication(
_clientId,
_clientAuthority,
_redirectUri,
_credential,
null,
_appTokenCache);
try
{
var result = await cca.AcquireTokenForClientAsync(_appScopes);
return result.AccessToken;
}
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Unable to authenticate. Unable to retrieve the access token for client."
});
}
}
}