TokenCache:在缓存中找不到匹配的令牌,Azure AD Api

时间:2017-07-11 08:13:32

标签: azure-active-directory access-token

我想使用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;
    }

我不知道问题是什么,在其他问题下我没有找到任何好的暗示,一些解释会有所帮助。当然,我想理解这一部分。

2 个答案:

答案 0 :(得分:1)

  • //当你打电话时

Main(){Method_A()}

aync Method_A(){await Method_B()}

任务< T> Method_B(){return T; }

//它将通过错误。 //需要将Mehtod_B保留在另一个任务中并运行。

//我在这里避免了几个asyncs

Main(){Method_A()}

Method_A(){Method_B()。Wait()}

Task Method_B(){return T; }

答案 1 :(得分:0)

在IIS进度中没有使用Console.WriteLine的输出。如果要在Web项目的输出窗口中输出结果,可以使用System.Diagnostics.Debug.WriteLine()方法。