c# - ADAL token 获取异常

标签 c# asp.net-mvc-4 adal

我已按照以下示例实现了 Azure AD 身份验证:

https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect

这是我的应用程序中的代码。用户收到间歇性异常“无法静默获取 token 。调用方法 token 获取”。任何帮助将不胜感激。

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
        {
            ClientId = ClientId,
            Authority = Authority,

            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                AuthorizationCodeReceived = (context) =>
                {
                    string userObjectId = null;
                    var code = context.Code;

                    var currentClaimsIdentity = context.AuthenticationTicket.Identity;
                    if (currentClaimsIdentity != null)
                    {
                        userObjectId = currentClaimsIdentity.FindFirst(Constants.ObjectIdentifierClaimType).Value;
                    }

                    ClientCredential credential = new ClientCredential(ClientId, AppKey);
                    AuthenticationContext authContext = new AuthenticationContext(Authority, new SessionCache(userObjectId, HttpContext.Current));
                    authContext.AcquireTokenByAuthorizationCode(code, StandardSettings.ReplyUrl, credential, Constants.GraphResourceBaseUrl);

                    return Task.FromResult(0);
                },

                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/");

                    return Task.FromResult(0);
                }
            }
        });



/// <summary>
    /// Gets the access token.
    /// </summary>
    /// <returns>The access token for service call.</returns>
    private string GetAccessToken()
    {
        string userName = null;
        AuthenticationResult authenticationResult = null;

        ClaimsPrincipal currentClaimsPrincipal = ClaimsPrincipal.Current;
        if (currentClaimsPrincipal != null)
        {
            userName = currentClaimsPrincipal.FindFirst(ClaimTypes.Name).Value;
        }

        try
        {
            authenticationResult = this.GetAuthenticationResult();

            if (authenticationResult.ExpiresOn < DateTimeOffset.UtcNow)
            {
                Trace.TraceWarning("Access token expired for the user: {0}. Challenge the user authentication to get a new token.", userName);
                this.httpCurrentContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
            }
        }
        catch (AdalSilentTokenAcquisitionException ex)
        {
            Trace.TraceWarning("Failed to acquire the token for the user: {0} with exception: {1}. Challenge the user authentication for retry.", userName, ex);
            this.httpCurrentContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }

        if (authenticationResult == null)
        {
            try
            {
                authenticationResult = this.GetAuthenticationResult();
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to acquire the token on the retry for the user: {0} with the exception: {1}.", userName, ex);
                throw new AdalException(
                    AdalError.FailedToAcquireTokenSilently,
                    "The session expired or the token cache was reset. Please sign out and then navigate to the url again to re-authenticate.");
            }
        }

        return authenticationResult.AccessToken;
    }

    /// <summary>
    /// Get the authentication result for the request.
    /// </summary>
    /// <returns>The authentication result.</returns>
    private AuthenticationResult GetAuthenticationResult()
    {
        string userObjectId = null;

        ClaimsPrincipal currentClaimsPrincipal = ClaimsPrincipal.Current;
        if (currentClaimsPrincipal != null)
        {
            userObjectId = currentClaimsPrincipal.FindFirst(Constants.ObjectIdentifierClaimType).Value;
        }

        AuthenticationContext authContext = new AuthenticationContext(
                   Startup.Authority,
                   new SessionCache(userObjectId, this.httpCurrentContext));

        ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.AppKey);
        return authContext.AcquireTokenSilent(
            Constants.GraphResourceBaseUrl,
            credential,
            new UserIdentifier(userObjectId, UserIdentifierType.UniqueId));
    }

最佳答案

出现该消息的原因有多种:

  • 您使用的缓存为空
  • 缓存不包含有效的刷新 token (已过期等)
  • 缓存不包含您指定的权限/客户端 ID/用户组合的刷新 token
  • 用户的标识符与 token 中最初颁发的实际用户标识符不对应

关于c# - ADAL token 获取异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32981920/

相关文章:

c# - 为整个项目全局命名空间别名

c# - Server.Transfer 到 HttpHandler

asp.net-mvc-4 - 如何使WebSecurity.Login使用用户名或电子邮件登录?

azure - 如何为 Azure 应用程序配置同意(AADSTS65005 错误)

android - Azure BLOB 存储 REST API - 使用 ADAL 访问 token 返回 403 和 404 错误

c# - C#中重载函数的执行顺序

c# - 评估数学表达式的最佳和最短方法

asp.net-mvc-4 - ASP.NET MVC 4 通过 ActionLink 传递对象变量

asp.net - 如何将 Controller 上未经授权的 Ajax 请求重定向到登录页面? 。

asp.net-mvc-5 - 指定重定向时 AAD 身份验证后的无限重定向循环