【发布时间】:2017-12-15 04:28:14
【问题描述】:
我想使用 Azure AD Api,但由于某种原因无法获取令牌。我有两种方法,调用后得到了这个:
TokenCache: No matching token was found in the cache iisexpress.exe Information: 0
这是我的代码:
public string GetToken()
{
string authority = "https://login.microsoftonline.com/{tenantId}/";
string clientId = "";
string secret = "";
string resource = "https://graph.windows.net/";
var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
//I think the problem is here:
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;
return token;
}
public string MakeRequest()
{
string accessToken = GetToken();
var tenantId = "";
string graphResourceId = "https://graph.windows.net/";
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
foreach (var user in client.Users.ExecuteAsync().Result.CurrentPage)
Console.WriteLine(user.DisplayName);
var client1 = new HttpClient();
var uri = "https://graph.windows.net/" + tenantId + "/users?api-version=1.6";
client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = client1.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
我不知道是什么问题,也没有找到任何很好的提示,在其他问题和一点解释下会有所帮助。我当然想了解这部分。
【问题讨论】:
-
你得到的详细错误是什么以及哪一行代码?代码似乎是正确的。您是否有足够的权限列出用户?例如,我们需要
User.Read.All或Directory.Read.All权限来执行此 REST。您可以从this site 解码访问令牌并检查roles声明。 -
iisexpress.exe 信息:...-AcquireTokenHandlerBase:=== 令牌获取已开始:授权:login.microsoftonline.com/tenantId 资源:graph.windows.net ClientId:...缓存类型:Microsoft.IdentityModel.Clients。 ActiveDirectory.TokenCache(0 项)身份验证目标:客户端 Microsoft.IdentityModel.Clients.ActiveDirectory 信息:2:... - TokenCache:在缓存 iisexpress.exe 中找不到匹配的令牌信息:0:... - TokenCache:否在缓存中找到匹配的令牌。 (反正角色似乎还可以)
-
这是adal的日志。预计当您第一次执行该方法时,无法从缓存中获取令牌。你的意思是没有异常,只拿到了上面的日志?
-
是的,我没有遇到异常。我试图在按下按钮后显示结果,我得到了这个并且网站刚刚加载......也许应该尝试异步编写它?
标签: azure-active-directory access-token