IdentityServer / IdentityServer3

OpenID Connect Provider and OAuth 2.0 Authorization Server Framework for ASP.NET 4.x/Katana
https://identityserver.github.io/Documentation/
Apache License 2.0
2.01k stars 762 forks source link

Critical problem with randomly infinite redirection #2496

Closed totpero closed 8 years ago

totpero commented 8 years ago

Hi,

I have one idsrv3 server and multiples asp mvc application clients. One of this application client randomly enter in infinite loop with idsrv3 application.

If i am already logged in this client with this problem and the cookies not expired, everything is OK even if this client app hosted on iis crash. If the client enter in this infinite loop if i try with other browser or other pc..this loop remains until reboot the client iis application. When this problem is active with this client, the idsrv works ok with other clients app.

The problem seems to be on this client app because this client not create User on this application, but why ?

This problem happens at random intervals of time. If i restart iis server everything returns to normal. I change the iis server but the problem persist. How i can view or log where is the problem on this OpenIdConnect client? Where is the problem?

brockallen commented 8 years ago

It's hard to tell from the limited information.

totpero commented 8 years ago

what you need? server and client configurations? server log?

brockallen commented 8 years ago

Sorry to answer this way, but I need you to debug it.

I can help if you have identified something something specific in IdSvr, but there's so much of your code, and Microsoft's code, and possibly other code, that's it's not my responsibility to debug your applications. Sorry.

totpero commented 8 years ago

but what can cause this problem? i copy client and server from repo samples. how can i debug? because i don't know when it is happening .

brockallen commented 8 years ago

You need to debug what is causing the MVC application to not accept the user's cookie or think the user is not allowed. Once it does, then it send the user to IdSvr. If the user is already logged into IdSvr, then the user will be sent back to the app. And the same request will be tried again.

So it sounds like an authorization problem in a certain request into your app.

totpero commented 8 years ago

When the client application trigger this problem i can't stop this problem only when i restart iis server. I try to remove all cookies, but the loop don't stop. on my controller client app i have only [Authorize] attribute without role, or user property. Can be something on SecurityTokenValidated in OpenIdConnectAuthenticationNotifications when the claim is mapped? But why this problem in random. Where i can debug the cookie binding to user?

vargamat commented 8 years ago

I have the same infinite redirection. If I use IIS Express just works fine but on IIS appear this problem. I tried to publish on an IIS with certificate but i got the same issue.

totpero commented 8 years ago

Can be the certificate the problem? I have the same https certificate to iis idsrv and the client with the problem. But why after restart the client iis then for some time time work.

totpero commented 8 years ago

One more thing: After few seconds of infinite loop i get this error Bad Request - Request Too Long something like this: https://github.com/IdentityServer/IdentityServer3/issues/1124 https://github.com/IdentityServer/IdentityServer3/issues/1407

totpero commented 8 years ago

The same problem i have also on idsrv3 now. This is my loop log:

2016-02-03 12:51:00.391 +02:00 [Information] Start authorize request
2016-02-03 12:51:00.391 +02:00 [Information] "Authorize request validation success"
 "{
  \"ClientId\": \"AUT/EXT\",
  \"ClientName\": \"AUT\",
  \"RedirectUri\": \"https://idsrv3site.com/\",
  \"AllowedRedirectUris\": [
    \"https://idsrv3site.com/\"
  ],
  \"SubjectId\": \"202\",
  \"ResponseType\": \"id_token token\",
  \"ResponseMode\": \"form_post\",
  \"Flow\": \"Implicit\",
  \"RequestedScopes\": \"openid email roles profile custom_profile\",
  \"State\": \"OpenIdConnect.AuthenticationProperties=_EVMHbAYdL8EIYsBSSoJkIGCAC4IiHTZ-2l7u32conBtI9ucHgbKAKLflIfBZRGvp1xbG07Jfw3ZrMj9zyxhkptU7mwl_3-JVr_ONHd03bvwAYvsvilkVKH-9Tdfd3pZEgh4wXP-h6VKuD7Xg54iKWyhgNB8HxoyyADdHAFjUR2aVQyVb-8Z0W_JQvZz9c6rBgzArfH8zC77g2_TLdyPLkZynylPh58ZsGrxhbqkKDs\",
  \"Nonce\": \"635900934602822839.ZDlhODUyOTAtYmFkYS00Y2E2LWE5YzctMzdlMmFkNmFlZDk0ZTc5ZTAzN2UtOTMzOS00YTg4LWEwNWItYzA3NDVhOTIyMjcy\",
  \"AuthenticationContextReferenceClasses\": [
    \"tenant:testclient.testtenant\"
  ],
  \"SessionId\": \"70f2a4b62b784a927b27e2781e4e3295\",
  \"Raw\": {
    \"client_id\": \"AUT/EXT\",
    \"redirect_uri\": \"https://idsrv3site.com/\",
    \"response_mode\": \"form_post\",
    \"response_type\": \"id_token token\",
    \"scope\": \"openid email roles profile custom_profile\",
    \"state\": \"OpenIdConnect.AuthenticationProperties=_EVMHbAYdL8EIYsBSSoJkIGCAC4IiHTZ-2l7u32conBtI9ucHgbKAKLflIfBZRGvp1xbG07Jfw3ZrMj9zyxhkptU7mwl_3-JVr_ONHd03bvwAYvsvilkVKH-9Tdfd3pZEgh4wXP-h6VKuD7Xg54iKWyhgNB8HxoyyADdHAFjUR2aVQyVb-8Z0W_JQvZz9c6rBgzArfH8zC77g2_TLdyPLkZynylPh58ZsGrxhbqkKDs\",
    \"nonce\": \"635900934602822839.ZDlhODUyOTAtYmFkYS00Y2E2LWE5YzctMzdlMmFkNmFlZDk0ZTc5ZTAzN2UtOTMzOS00YTg4LWEwNWItYzA3NDVhOTIyMjcy\",
    \"acr_values\": \"tenant:testclient.testtenant\"
  }
}"
2016-02-03 12:51:00.407 +02:00 [Information] Creating Implicit Flow response.
2016-02-03 12:51:00.422 +02:00 [Information] Getting claims for identity token for subject: 202
2016-02-03 12:51:00.516 +02:00 [Information] End authorize request
2016-02-03 12:51:00.516 +02:00 [Information] Posting to https://idsrv3site.com/
--------
2016-02-03 12:51:00.656 +02:00 [Information] Start userinfo request
2016-02-03 12:51:00.656 +02:00 [Information] Token found: AuthorizationHeader
2016-02-03 12:51:00.656 +02:00 [Information] Start access token validation
2016-02-03 12:51:00.672 +02:00 [Information] "Token validation success"
"{
  \"ValidateLifetime\": true,
  \"AccessTokenType\": \"Jwt\",
  \"ExpectedScope\": \"openid\",
  \"Claims\": {
    \"iss\": \"idsrv3\",
    \"aud\": \"idsrv3/resources\",
    \"exp\": \"1454500260\",
    \"nbf\": \"1454496660\",
    \"client_id\": \"AUT/EXT\",
    \"scope\": [
      \"openid\",
      \"email\",
      \"roles\",
      \"profile\",
      \"custom_profile\"
    ],
    \"sub\": \"202\",
    \"auth_time\": \"1454496647\",
    \"idp\": \"LDAP\",
    \"amr\": \"external\"
  }
}"
2016-02-03 12:51:00.672 +02:00 [Information] Creating userinfo response
2016-02-03 12:51:00.672 +02:00 [Information] Scopes in access token: "openid email roles profile custom_profile"
2016-02-03 12:51:00.672 +02:00 [Information] Requested claim types: "sub email email_verified role name family_name given_name middle_name nickname preferred_username profile picture website gender birthdate zoneinfo locale updated_at name given_name family_name address function organization is_local full_name account CNP"
2016-02-03 12:51:00.703 +02:00 [Information] Profile service returned to the following claim types: "sub family_name given_name address function organization full_name is_local preferred_username account role"
2016-02-03 12:51:00.703 +02:00 [Information] End userinfo request
2016-02-03 12:51:00.703 +02:00 [Information] Returning userinfo response.

And this part is repeated indefinitely. Where is the problem? I don't know what to do.

totpero commented 8 years ago

What other alternatives to OpenIdConnect i can use with the same result?

leastprivilege commented 8 years ago

Authentication seems to work fine - it must be an issue in your client.

totpero commented 8 years ago

After OpenIdConnectAuthenticationOptions->Notifications->SecurityTokenValidated what is executed because in controller[Authorize] and User.Identity.IsAuthenticate is False. Can be the problem if i use the same certificate "*.domain.com" on clients and server if all is subdomain of my domain certificate?

leastprivilege commented 8 years ago

In the SecurityTokenValidated notification - you can find the ext user on the AuthenticationTicket.

If that is OK - then something is wrong with your cookie setup.

totpero commented 8 years ago

my cookie config is:

app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType ,
            });
totpero commented 8 years ago

in idsrv log file i found many of this error the same issues https://github.com/IdentityServer/IdentityServer3/issues/2232:

2016-02-04 11:20:18.725 +02:00 [Error] Unhandled exception
System.Web.HttpException (0x800704CD): The remote host closed the connection. The error code is 0x800704CD.
   at System.Web.Hosting.IIS7WorkerRequest.RaiseCommunicationError(Int32 result, Boolean throwOnDisconnect)
   at System.Web.Hosting.IIS7WorkerRequest.ExplicitFlush()
   at System.Web.HttpResponse.Flush(Boolean finalFlush, Boolean async)
   at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size)
   at System.IO.Stream.<BeginWriteInternal>b__11(Object param0)
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.IO.Stream.EndWrite(IAsyncResult asyncResult)
   at Microsoft.Owin.Host.SystemWeb.CallStreams.OutputStream.EndWrite(IAsyncResult asyncResult)
   at System.Net.Http.StreamToStreamCopy.BufferWrittenCallback(IAsyncResult ar)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<SendResponseContentAsync>d__20.MoveNext()
leastprivilege commented 8 years ago

That's unrelated. That's the browser aborting requests before Web API could close the connection.

totpero commented 8 years ago

The problem seems to be similar with: https://github.com/IdentityServer/IdentityServer3/issues/294 https://github.com/IdentityServer/IdentityServer3/issues/1765 https://github.com/aspnet/Security/issues/179 https://github.com/NWebsec/NWebsec/issues/65

I solve this problem by adding this line in Global.asax:

protected void Session_Start() { }

Suggestion: Make list with frequent problem and how to solve, in documentation page.

sellotape commented 8 years ago

@totpero In what order in startup.cs do you call UseCookieAuthentication() and UseOpenIdConnectAuthentication()?

totpero commented 8 years ago

@sellotape I use first UseCookieAuthenticationand after UseOpenIdConnectAuthenticatio. Obs. : This problem is solved without downgrade Microsoft.Owin.Security.OpenIdConnect from 3.0.1 to 3.0.0, only with empty Session_Start in Global.asax

sellotape commented 8 years ago

@totpero Okay - probably worth noting (for others, perhaps) that in the simplest possible example, if you put UseCookieAuthentication() after UseOpenIdConnectAuthentication(), you will get an infinite loop, presumably because the authentication middleware is then running first and redirecting to the STS, thinking the user is not authenticated, as the cookie middleware hasn't yet established that fact. Swapping the order will fix that particular issue.

michaelvperry commented 8 years ago

@totpero Early days yet but on mine the Session start entry fixes it. I'm new to this so I'd love to know exactly why this fixes it?

Also is this a bug as I'm on an app that has little more than the boilerplate MVC code and was getting this? Oddly I'm sure there wasn't this issue a few weeks ago as the original program was an App for SharePoint, and it just died one day.

Edit, Actually never mind. I re-read the linked posts and sort of understand it now. I think my use of a session variable has triggered the known OWIN cookie issue.

brockallen commented 8 years ago

Has this been sorted out? Can we close it?

diegobfernandez commented 8 years ago

Same to me! Adding protected void Session_Start() { } worked it out.

abcplex commented 8 years ago

Getting same issue random redirect loops.

UlyssesAlves commented 7 years ago

In my case (development environment) the problem was because my server was configured to run through SSL (https), but when I started debugging the website, Visual Studio would open it with HTTP port instead of HTTPS port, so when I clicked on a link to a protected resource, after authenticating the user IdentityServer tried to redirect this user to the HTTP PORT version of my website, which returned 302 HTTP status, and then the website kept trying to access this address endlessly.

To stop this from happen, after I start debugging the website, I closed the website open on HTTP port and pasted on the browser URL the HTTPS port address of the website. So, all the links to the protected resources are now rendered to access the HTTPS version of the website, so the redirection after authentication works as expected and no loop occurs anymore.

jhasselkus commented 7 years ago

Can anyone explain why adding protected void Session_Start() { } fixes this (in at least some cases)?

michaelvperry commented 7 years ago

According to parkinsona in the other thread (https://github.com/IdentityServer/IdentityServer3/issues/294), it creates a blank sessionid cookie which works around a flaw in the katana middleware.

Ahoapap commented 7 years ago

I encountered this issue and applied ALL THE FIXES ON THE INTERNET. None of them worked, then I went in and looked at my cookie. It was huge. Owin middleware was truncating it and then then [Authorize] attribute wasn't able to verify the identity -> send user to oidc -> identity good -- redirect to client -> truncate cookie -> can't verify in [Authorize] -> send user to oidc -> etc.

The fix was in Microsoft.Owin.Host.SystemWeb 3.1.0.0 and using the SystemWebChunkingCookieManager.

It'll split the cookies and parse them together.

  app.UseCookieAuthentication(new CookieAuthenticationOptions
  {
      AuthenticationType = "Cookies",
      CookieManager = new Microsoft.Owin.Host.SystemWeb.SystemWebChunkingCookieManager()
  });
Ben-Pattinson commented 7 years ago

Yup the Voodoo protected void Session_Start() { } fixed it. Thanks!