Paudel
Paudel

Reputation: 11

Secure ASP.NET Core 3.1 MVC app with KeyCloak

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

I tried few things:

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.

Upvotes: 1

Views: 1720

Answers (1)

OnderD
OnderD

Reputation: 666

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.

Upvotes: 0

Related Questions