【问题标题】:Token issues in b2c-dotnet-webapp-and-webapib2c-dotnet-webapp-and-webapi 中的令牌问题
【发布时间】:2017-08-17 15:16:27
【问题描述】:

我创建了一个 b2c-dotnet-webapp-and-webapi 类型的应用程序。但是 20 分钟后或某个时间后(近 30 分钟不确定)我的 WebApp 在 Ajax 调用期间抛出异常,说 401(未授权)。当 ajax 调用命中 WebApp 控制器时出现此异常所以此错误来自 OWIN 中间件不确定原因。

我的 Startup.cs 设置是

public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CPasswordResetPolicy));
            app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(_aadB2CSignInPolicy));
        }

        private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
        {
            context.HandleResponse();
            if (context.Exception is OpenIdConnectProtocolInvalidNonceException &&
                context.Exception.Message.Contains("IDX10316"))
            {
                // Redirect to the originally requested URL
                context.Response.Redirect(context.Request.Uri.PathAndQuery);
            }
            else
            {
                var trackingId = Guid.NewGuid().ToString("N");
                _telemetry.TrackException(
                    context.Exception,
                    new Dictionary<string, string> {{"SignInErrorTrackingId", trackingId}});
                context.Response.Redirect($"/Home/SignInError?trackingId={trackingId}");
            }
            return Task.FromResult(0);
        }

        private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
        {
            return new OpenIdConnectAuthenticationOptions
            {
                // For each policy, give OWIN the policy-specific metadata address, and
                // set the authentication type to the id of the policy
                MetadataAddress = string.Format(_aadInstance, _tenant, policy),
                AuthenticationType = policy,

                // These are standard OpenID Connect parameters, with values pulled from web.config
                ClientId = _clientId,
                RedirectUri = _redirectUri,
                PostLogoutRedirectUri = _redirectUri,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed,
                },
                Scope = "openid",
                ResponseType = "id_token",

                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    SaveSigninToken = true,
                },
            };
        }
    } 

如果我要修改代码

app.UseCookieAuthentication(new CookieAuthenticationOptions { SlidingExpiration = true, ExpireTimeSpan = TimeSpan.FromMinutes(60) });, 并在 OpenIdConnectAuthenticationOptions 中添加以下设置 UseTokenLifetime = false,

然后我的 WebApp 工作了 1 小时,之后我再次面临 401 Unauthorized。这次我的 WEAPI 给出了这个错误,因为我猜默认令牌的有效期为 1 小时。

问题:如果令牌在 ajax 调用期间 1 小时后过期,我该如何管理令牌问题?以及我应该拥有的最佳设置是什么,以便我的中间件在 20 分钟或随机时间后不会给我 401?

如果我做错了什么,请忽略。我对此很陌生,没有太多想法。

【问题讨论】:

    标签: c# oauth asp.net-web-api2 owin azure-ad-b2c


    【解决方案1】:

    你在正确的轨道上!您需要注意以下几点:

    Azure AD B2C 返回的所有令牌都有过期时间。 x 分钟后,您的 id 令牌过期。您需要通过重新登录过程再次获取新的 id 令牌。

    因为每 x 分钟登录一次很烦人,所以您可以在用户第一次登录时请求刷新令牌。当 id 令牌过期时,可以将刷新令牌发送到 Azure AD B2C 以获取新的 id 令牌。

    部分刷新令牌实现由库自动执行,但这是您需要实现的:

    1. 通过在 responseType 变量中添加“code”并在范围变量中添加“offline_access”来请求除 id 令牌之外的代码。
    2. 用代码交换刷新令牌并将令牌存储在缓存中。
    3. 在调用 Web api 之前从缓存中获取令牌。如果令牌过期,库会在将其从缓存中拉出之前自动为您续订。

    所有这些都在这个example 中完成。您只需要更新范围(未指定时的默认 responseType 为“code id_token”)。

    注意:我们启用了access tokens 并使用它更新了示例。请使用此更新的示例。您的代码反映了旧示例。我还建议在调用 Web API 时使用访问令牌而不是 id 令牌。

    【讨论】:

    • 抱歉回复晚了。正如你所建议的,我实现了刷新令牌部分。截至目前,它的工作正常。但是现在我在登录 Azure 页面时遇到了非常频繁的问题。 IE。我收到错误 400 Request Header is Too Large 这个问题来了,因为现在我的 cookie 太大了,因为将所有令牌都保留在上下文中。关于这个问题的任何建议。好吧,当用户退出时,我将删除所有 cookie。但它看起来有时它不起作用。
    猜你喜欢
    • 1970-01-01
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2019-09-22
    相关资源
    最近更新 更多