Search code examples
c#asp.net-web-apioauth-2.0keycloakopenid-connect

WebAPI2: Authorization code flow in micro services architecture


Identity Provider: Keycloak-9.0.0 .net version: 4.5.2

Basically i am trying to integrate c# webapi service as shown in the below.

Authorization code flow

I have used the Keycloak connector( https://github.com/mattmorg55/Owin.Security.Keycloak ) for C# which is designed as an OWIN authentication middleware component

With the keycloak sample i get errors. But i am not sure if the the call gets forwarded to keycloak for validation instead i get an error.

  1. If WebAPI mode is not enabled i get "signature-validation-failed-unable-to-match-kid"
  2. If webAPI mode is enabled i get 401 ({"Message":"Authorization has been denied for this request."}Access Unauthorized: Requires valid bearer token authorization header

startup class

public void Configuration(IAppBuilder app)
        {

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Bearer"
            });



            app.UseKeycloakAuthentication(new KeycloakAuthenticationOptions
            {
                Realm = "test_keycloak",
                ClientId = "test",
                ClientSecret = "9f25fd55-851f-4eed-9fb9-24a0a0e4ff11",

                KeycloakUrl = "http://localhost:8080/auth",
                AuthenticationType = "Bearer",
                SignInAsAuthenticationType = "Bearer",

                AllowUnsignedTokens = false,
                DisableIssuerSigningKeyValidation = false,
                DisableIssuerValidation = false,
                UseRemoteTokenValidation = true,
                EnableWebApiMode = true,
                DisableAudienceValidation = false,
                Scope= "openid",

            });
}

I don't see any logs in keycloak. What could be going wrong ? how do i debug?

Since its a standard Oauth2 flow, will i be able do use Microsoft.Owin.Security.OpenIdConnect for the token validation?

For example in java spring security has easy configurations for the same(with jwt-cert -url)

Need your inputs!


Solution

  • I could solve with microsoft.owin.security.jwt as well. Here is the code.

    Note: haven't done exception handling. just basic code.

    public void Configuration(IAppBuilder app) {
            HttpClient htpp = new HttpClient();
            var keysResponse = htpp.GetAsync("https://<FQDN of keycloak>/auth/realms/<realm>/protocol/openid-connect/certs").Result;
            
            var rawKeys = keysResponse.Content.ReadAsStringAsync().Result;
            
    
            Microsoft.IdentityModel.Tokens.JsonWebKeySet jsonWebKeySet = JsonConvert.DeserializeObject<Microsoft.IdentityModel.Tokens.JsonWebKeySet>(rawKeys);
    
            app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions {
                AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
                AuthenticationMode = AuthenticationMode.Active,
                Realm = <realm>",
                
                TokenValidationParameters = new TokenValidationParameters() {
                    
                    AuthenticationType = "Bearer",
                    ValidateIssuer = true,
                    ValidateIssuerSigningKey = true,
                    ValidAudiences = new string[] { <clientID> },
                    ValidIssuer = "<FQDN of keycloak>/auth/realms/<realm>",
                    ValidateLifetime = true,
                    ValidateAudience = true,
                    IssuerSigningKeys = jsonWebKeySet.GetSigningKeys(),
                    
                }
            });
        }