mattmorg55 / Owin.Security.Keycloak

Keycloak Authentication Middleware for the C# OWIN Pipeline
http://keycloak.jboss.org
MIT License
17 stars 20 forks source link

Sample code does not execute because redirect does not work (I guess) #18

Open peddanet opened 4 years ago

peddanet commented 4 years ago

Hi all, hi Matt,

[EDIT] Ok, I see the interface is (partly?) described here: KeyAuthenticationOptions.cs

How can I set the auto refresh token string, for example?

I have found in a python project at our site the following instanciation of KeyCloakAdmin:

        self.cloak = KeycloakAdmin(
            server_url=KEYCLOAK.url,
            realm_name="Kostal",
            username=KEYCLOAK.username,
            password=KEYCLOAK.password,
            client_secret_key=KEYCLOAK.secret_key,
            verify=True,
            auto_refresh_token=['get', 'put', 'post', 'delete']
        )

I don't know if this is working, but at least it has some implementational details like auto refresh token (which looks like REST services) /EDIT]

I want kindly use your code in my project to access our already set up key cloak server (different person). I got the json OICD from our keycloak server:

{
  "realm": "xxx",
  "auth-server-url": "xxx",
  "ssl-required": "external",
  "resource": "JustificationQualifier",
  "credentials": {
    "secret": "xxx"
  },
  "confidential-port": 0
}

cause there is no other possibility to contact you directly, I try this way, hope you don't mind!

First I tried out your sample but find out that your test server (which configuration?) is not online available (for me). So I tried your code and changed the startup.cs according to the readme.txt as far as I understood.

And it throws an exception in GenericMessage.cs in your keycloak identity lib: [Exception: HTTP client returned an unrecoverable error] Keycloak.IdentityModel.Models.Messages.<SendHttpPostRequest>d__5.MoveNext() in C:\GITHUB\mattmorg55\Owin.Security.Keycloak\src\Keycloak.IdentityModel\Models\Messages\GenericMessage.cs:39 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Keycloak.IdentityModel.Models.Messages.<ExecuteHttpRequestAsync>d__8.MoveNext() in C:\GITHUB\mattmorg55\Owin.Security.Keycloak\src\Keycloak.IdentityModel\Models\Messages\RequestAccessTokenMessage.cs:33 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Keycloak.IdentityModel.Models.Messages.<ExecuteAsync>d__7.MoveNext() in C:\GITHUB\mattmorg55\Owin.Security.Keycloak\src\Keycloak.IdentityModel\Models\Messages\RequestAccessTokenMessage.cs:27 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Keycloak.IdentityModel.<ConvertFromAuthResponseAsync>d__29.MoveNext() in C:\GITHUB\mattmorg55\Owin.Security.Keycloak\src\Keycloak.IdentityModel\KeycloakIdentity.cs:218 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Owin.Security.Keycloak.Middleware.<InvokeAsync>d__1.MoveNext() in C:\GITHUB\mattmorg55\Owin.Security.Keycloak\src\Owin.Security.Keycloak\Middleware\KeycloakAuthenticationHandler.cs:79 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +435 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69 Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64 System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +389 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

So I guess, something is wrongly configured, which brings me to my question:

How did you configure your server? Did you use ssl? Can you give me any hint?

startup.cs (changed):
    public class Startup
    {
        const string persistentAuthType = "keycloak_cookies"; // Or name it whatever you want
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = persistentAuthType
            });

            // You may also use this method if you have multiple authentication methods below,
            // or if you just like it better:
            app.SetDefaultSignInAsAuthenticationType(persistentAuthType);

            app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
            {
                Realm = "xxx",
                ClientId = "JustificationQualifier",
                ClientSecret = "xxx",
                KeycloakUrl = "xxx",
                //ResponseType = "id_token token",
                AuthenticationType = persistentAuthType,
                //AuthenticationMode = AuthenticationMode.Active,
                SignInAsAuthenticationType = persistentAuthType, // Not required with SetDefaultSignInAsAuthenticationType
                                                                 //Token validation options - these are all set to defaults
                AllowUnsignedTokens = false,
                DisableIssuerSigningKeyValidation = false,
                DisableIssuerValidation = false,
                DisableAudienceValidation = false,
                TokenClockSkew = TimeSpan.FromSeconds(2)
            });
}}}

Appreciate any hint! I am totally new to keycloak, and unfortunately I have to use c# (which is only unfortunately as java/groovy would have been a choice of more initial informatioN).

BR Peter

peddanet commented 4 years ago

Ok the problem is the redirecting to localhost. The server does not know where to redirect exactly:

Request link: http://debekube002.de.kostal.int:30065/auth/realms/Kostal/protocol/openid-connect/auth?redirect_uri=http:%2F%2Flocalhost:5232%2Fowin%2Fsecurity%2Fkeycloak%2Fkeycloak_cookies%2Fcallback&response_type=code&scope=openid&state=oidc_state_f7432081d311458e8187c3a7bf10b134&client_id=JustificationQualifier&client_secret=62edfa53-e038-47e4-a901-5fef1687024d

Answerlink: http://localhost:5232/owin/security/keycloak/keycloak_cookies/callback?state=oidc_state_f4dd2b3e087e40029eaef8b34a715d25&session_state=d9ef5256-21e8-489f-93a5-df90992739e9&code=610e1ece-932f-48f6-8ead-b3c0e2fcbc1f.d9ef5256-21e8-489f-93a5-df90992739e9.4eb33907-f7a2-4e9e-84fb-7be3118d71ba

I have found localhost only in an "exclude" list in the project:

        <Add Type="Microsoft.ApplicationInsights.DependencyCollector.DependencyTrackingTelemetryModule, Microsoft.AI.DependencyCollector">
            <ExcludeComponentCorrelationHttpHeadersOnDomains>
                <!-- 
        Requests to the following hostnames will not be modified by adding correlation headers. 
        This is only applicable if Profiler is installed via either StatusMonitor or Azure Extension.
        Add entries here to exclude additional hostnames.
        NOTE: this configuration will be lost upon NuGet upgrade.
        -->
                <Add>core.windows.net</Add>
                <Add>core.chinacloudapi.cn</Add>
                <Add>core.cloudapi.de</Add>
                <Add>core.usgovcloudapi.net</Add>
                <Add>localhost</Add>
                <Add>127.0.0.1</Add>
            </ExcludeComponentCorrelationHttpHeadersOnDomains>
        </Add>

Where can I configure the redirect URL Login Screen with Redirect before logging in 2020-07-13 10_57_09-Window Login Screen with Redirect after logging in 2020-07-13 10_57_09-Window

in the project?

See attached pics.

peddanet commented 4 years ago

Is this project dead? Thanks for any help anyway. I have now find the old school way to work with OIDC and RestClient directly...