1

I am trying to secure my ASP.NET Core 3.1 MVC app with KeyCloak.

I tried few things:

  • I used some of the examples available but they are either deprecated or done in .NET Core 2.1
  • I found some KeyCloak adapters for .NET Core but they are not maintained for so long.
  • I found one GitHub repo from thinktecture-labs webinar for keycloak securing Angular app and API but could not figure out the KeyCloak client configuration as well as how to connect it to ASP.NET Core MVC app in a similar way.

I would really appreciate it if you can guide me with any blog, GitHub repo, or a simple example that shows how to secure an ASP.NET Core 3.1 MVC app with KeyCloak. Thanks a lot in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Paudel
  • 11
  • 3

1 Answers1

0

You don't need to use keycloak-specific libraries to integrate Keycloak with ASP.NET Core 3.1. You can use JWT token authentication / authorization libraries instead.

Sample: Add the following lines to your appsettings.json file. Please don't forget to change the section to your realm name.

"JWT": {
  "Issuer": "https://<keycloakdomain>/auth/realms/<realmname>",
  "Audience": "account, <realmname>, <anotherrealmname>"
}

You can type the following code into your startup.cs file.

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Authority = Configuration["JWT:Issuer"];
                x.IncludeErrorDetails = true;
                x.SaveToken = true;
                x.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context => { return Task.CompletedTask; },
                    OnTokenValidated = context => { return Task.CompletedTask; }
                };
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = true,
                    ValidAudiences = (Configuration["JWT:Audience"]).Split(','),
                    ValidateIssuerSigningKey = true,
                    ValidateIssuer = true,
                    ValidIssuer = Configuration["JWT:Issuer"],
                    ValidateLifetime = false
                };
        
                x.Validate();
                x.Events = new JwtBearerEvents()
                {
                    OnAuthenticationFailed = autFailed =>
                    {
                        autFailed.NoResult();
                        autFailed.Response.StatusCode = 401;
                        autFailed.Response.ContentType = "text/plain";
                        return autFailed.Response.WriteAsync(autFailed.Exception.ToString());
                    }
                };
            });

After these operations, you can see the token validation by sending Bearer ... as the Authorization header value.

OnderD
  • 456
  • 4
  • 4
  • Thanks a lot, @OnderD for your prompt response. I am wondering how do I configure the KeyCloak for this client, which "Access type" to choose, "Confidential" or "Bearer Only"? How do I configure it so that it will work for the role-based Authorization? – Paudel May 23 '21 at 08:21
  • You can choose "Confidential". And you can choose Authorization Enable = true for RBAC – OnderD May 24 '21 at 10:27
  • Then how should I introduce the ClientId and ClientSecret in my Startup.cs or in appsettings.json. Can I introduce roles in the controller's action like [Authorize(Roles = "Customer-Admin")]? Most of the information I found for this approach is for Core API but I couldn't find any appropriate ones for the MVC. Do you think this approach is good for the .Net Core MVC app? I followed the answer by @Imagin8 (https://stackoverflow.com/questions/41721032/keycloak-client-for-asp-net-core). RBAC is working but while inspecting in jwt.io I can't see roles and profile parameters in the access token. – Paudel May 25 '21 at 11:36