ASP.NET Core (API, Blazor and MVC) + Keycloak — Part 2

Luy Lucas
3 min readJan 28, 2024

In this part 2, We’ll connect an API with one client

Part 1;

Part 3;

Part 4;

Bonus;

With Visual Studio 2022, Visual Studio Code, Jetbrains Rider, or your favorite IDE, create a solution and add an ASP.NET API app with no authentication and add these packages:

Install-Package Keycloak.AuthServices.Authentication

Install-Package Keycloak.AuthServices.Authorization

These two packages from GitHub have all the configurations needed to connect the API to Keycloak. In the Keycloak Administration Panel, select the ASP.NET realm, go to ‘clients’ and copy the client settings:

In the ‘appsettings.development’, create a new section called ‘Keycloak’ and paste this JSON:

SSL is not used because this is just a development example. You will need to configure this for your production scenario. Now, in the ‘Program.cs’ file, we’ll register the authentication and authorization services:

We can use Keycloak with Swagger too. Just paste this configuration:

Don’t forget to register the middlewares. I’ve disabled CORS for this example:

Before run this, We need to register the URI as valid in Keycloak client. We can copy the registred valid redirect URI from Keycloak client to API launch settings or copy the url from launch settings and input as valid URI on the keycloak client. We just need to have the app URI on keycloak client.

For this example, I have changed API launchsettings:

That’s all we need. Run this, and on Swagger, click ‘Authorize’:

Search for ‘implicit’ and enter the client ID:

Click on ‘Authorize’. This will redirect you to the Keycloak login page:

Use the usertest1 credentials and voilá:

Now, you can generate tokens from the Keycloak API and use them directly as bearer tokens for the API.

This source is in my GitHub and I used this repo from this article to build this.

Next, we’ll do this with ASP.NET Core MVC.

Cya.

--

--