AdalSilentTokenAcquisitionException:由于未在缓存中找到令牌,因此无法以静默方式获取令牌。调用方法AcquireToken

时间:2016-09-28 20:12:46

标签: c# azure asp.net-core-mvc microsoft-graph

尝试对此示例app进行反向工程。只有我没有创建自己的服务,只是尝试使用Microsoft Graph API获取我的个人资料信息。得到以下错误:

AdalSilentTokenAcquisitionException:由于未在缓存中找到令牌,因此无法以静默方式获取令牌。调用方法AcquireToken

我对此很新,但我已经完成了与该错误相关的所有stackoverflow问题,并且无法弄明白。

我正在使用Asp.net核心最新版本。我总是在AcquireTokenSilentAsync上出现上述错误。任何提示或想法都会有所帮助。

以下是我到目前为止的情况。

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        app.UseApplicationInsightsRequestTelemetry();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseApplicationInsightsExceptionTelemetry();

        app.UseStaticFiles();

        app.UseSession();

        //app.UseCookieAuthentication();

        // Populate AzureAd Configuration Values
        Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"];
        ClientId = Configuration["Authentication:AzureAd:ClientId"];
        ClientSecret = Configuration["Authentication:AzureAd:ClientSecret"];
        GraphResourceId = Configuration["Authentication:AzureAd:GraphResourceId"];
        GraphEndpointId = Configuration["Authentication:AzureAd:GraphEndpointId"];

        // Configure the OWIN pipeline to use cookie auth.
        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            ClientId = ClientId,
            ClientSecret = ClientSecret,
            Authority = Authority,
            CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            GetClaimsFromUserInfoEndpoint = false,

            Events = new OpenIdConnectEvents
            {
                OnRemoteFailure = OnAuthenticationFailed,
                OnAuthorizationCodeReceived = OnAuthorizationCodeReceived,
            }

        });

OnAuthorizationCodeReceived:

private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
    {
        // Acquire a Token for the Graph API and cache it using ADAL.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
        string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
        AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);

        // Notify the OIDC middleware that we already took care of code redemption.
        context.HandleCodeRedemption();



    }

MyProfileController:

public async Task<IActionResult> Index()
    {
        AuthenticationResult result = null;
        var user = new ADUser();

        try
        {
            string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
            ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
            var tc = authContext.TokenCache.ReadItems();
            result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.RequiredDisplayableId));

            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                String responseString = await response.Content.ReadAsStringAsync();
                List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
            }
        }
        catch (Exception)
        {

            throw;
        }
        return View();
    }

2 个答案:

答案 0 :(得分:1)

我建议使用UserIdentifierType.UniqueId作为示例does。使用错误的标识符类型可能导致缓存未命中。如果库无法找到令牌缓存条目,则会因此错误而失败,您需要再次请求用户登录。如果你已经尝试过这个并且它没有用,请告诉我。

答案 1 :(得分:0)

AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,                     新的NaiveSessionCache(userObjectID));

调试此行并检查数据的authContext缓存字典表。如果记录为0,则询问/重定向用户登录。一旦用户登录缓存表应填写并且toke应该可用。

AuthenticationContext authContext = new AuthenticationContext(Startup.Authority,
                        new NaiveSessionCache(userObjectID));
                    if (authContext.TokenCache.Count == 0)
                    {
                        authContext.TokenCache.Clear();
                        CosmosInterface.Utils.AuthenticationHelper.token = null;
                        HttpContext.GetOwinContext().Authentication.SignOut(
                            OpenIdConnectAuthenticationDefaults.AuthenticationType,
                            CookieAuthenticationDefaults.AuthenticationType);
                    }