首页 > 解决方案 > Azure AD 身份验证在会话超时时中断 HTTP 发布操作

问题描述

我最近使用“开箱即用”代码从 Windows 身份验证更改为 Azure AD;

    public void ConfigureAuth(IAppBuilder app)
    {

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseKentorOwinCookieSaver();
        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = Authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
                    AuthorizationCodeReceived = (context) =>
                    {
                        var code = context.Code;
                        ClientCredential credential = new ClientCredential(clientId, appKey);
                        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                        //AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
                        AuthenticationContext authContext = new AuthenticationContext(Authority);
                        return authContext.AcquireTokenByAuthorizationCodeAsync(
                           code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
                    }
                }
            });
    }

我们的用户在尝试提交某些表单时开始出现间歇性 404 错误。我想我已经设法通过删除 cookie 来重现这个问题,所以我怀疑它与会话自然超时的时间有关。

如果我查看带有 HTTP GET 请求的流程,它看起来像;

一切都是一种享受...

但是对于 HTTP POST;

失败,因为端点只接受 HTTP POST 请求。

知道是否/如何解决这个问题吗?我会认为内置的状态跟踪或它正在做的任何事情都会存储原始请求并继续它离开的地方,不管......

标签: c#httpazure-active-directoryowin

解决方案


看起来您没有使用令牌缓存。这意味着用户的会话将在他们登录应用程序后大约一个小时后过期。

要解决此问题,您应该在应用程序需要访问令牌时使用 AcquireTokenSilentAsync。此方法将使用它的内存缓存自动为您刷新令牌。有关更多详细信息,请参阅https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/AcquireTokenSilentAsync-using-a-cached-token


推荐阅读