与Asp.net应用程序一起使用的OpenIdConnectAuthentication进入AuthorizationCodeReceived的无限循环

时间:2017-07-31 07:28:46

标签: c# asp.net owin openid azure-active-directory

我正在使用Owin,我的asp.net应用程序的OpenId身份验证来验证Azure登录用户。但是一旦我从azure和重定向完成登录,AuthorizationCodeReceived就会进入无限循环。以下是我使用的代码。

我已尝试过以下不同帖子的各种建议,但这对我没有帮助。

  • https://github.com/IdentityServer/IdentityServer3/issues/3239

  • infinite loop going back to authentication page when using OAuth in MVC5

  • Second sign-in causes infinite redirect loop after the first successful login MVC .NET 5 OWIN ADAL OpenIDConnect
  • 设置Call​​backPath

    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseKentorOwinCookieSaver(); //did not work
        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            //CookieHttpOnly = false, 
            //CookieSecure = CookieSecureOption.SameAsRequest, //Did not work
            //CookieManager = new SystemWebCookieManager() //did not work
            AuthenticationType = "Cookies"
        }
        );
        app.UseOpenIdConnectAuthentication(
            new OpenIdConnectAuthenticationOptions
            {
                ClientId = clientId,
                Authority = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri = postLogoutRedirectUri,
                CallbackPath = new PathString("/my_Azure/Start.aspx"),
    
                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;
                        Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority, new ADALTokenCache(signedInUserID));
                        AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
    
                        return Task.FromResult(0);
                    }
                }
            }
            );
    
    
        // This makes any middleware defined above this line run before the Authorization rule is applied in web.config
        app.UseStageMarker(PipelineStage.Authenticate);
    

1 个答案:

答案 0 :(得分:0)

问题在于web.config中的授权设置,我使用了deny <deny users="*"/>这导致应用程序拒绝所有授权因此进入循环,当我将其更改为<deny users="?"/>时它开始工作得很好。