【问题标题】:AdalSilentTokenAcquisitionException: Failed to acquire token silently as no token was found in the cache. Call method AcquireTokenAdalSilentTokenAcquisitionException:无法静默获取令牌,因为在缓存中未找到令牌。调用方法 AcquireToken
【发布时间】:2016-09-28 20:12:46
【问题描述】:

试图对这个样本app进行逆向工程。只有我没有创建自己的服务,只是尝试使用 Microsoft Graph API 获取我的个人资料信息。收到以下错误:

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

我对此很陌生,但我已经解决了与该错误相关的所有 stackoverflow 问题,但无法弄清楚。

我正在使用 Asp.net core 最新版本。我总是因 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();



    }

我的配置文件控制器:

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();
    }

【问题讨论】:

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


    【解决方案1】:

    我建议使用UserIdentifierType.UniqueId 作为示例does。使用错误的标识符类型会导致缓存未命中。如果库找不到令牌缓存条目,它将失败并出现此错误,您需要要求用户再次登录。让我知道您是否已经尝试过但没有成功。

    【讨论】:

    • 感谢您回复我。我试过了,它仍然不起作用。但是,我确实注意到,如果我在这一行设置一个断点: result = await authContext.AcquireTokenSilentAsync(Startup.GraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));然后等待几分钟,代码将继续运行而不会出现错误。
    • 您能否使用 ADAL 日志和/或网络跟踪更新问题?从 ADAL 收集日志的临时说明如下:github.com/AzureAD/azure-activedirectory-library-for-dotnet/…。重要的网络跟踪将是 login.microsoftonline.com 的任何会话
    【解决方案2】:

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

    调试此行并检查 authContext 缓存字典表中的数据。如果记录为 0,则要求/重定向用户登录。一旦用户登录缓存表应该被填充并且应该可以使用。

    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);
                        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2015-07-10
      • 1970-01-01
      相关资源
      最近更新 更多