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

Luy Lucas
2 min readJan 28, 2024

--

In this part, we’ll configure a Blazor app to use Keycloak as SSO.

Part 1;

Part 2;

Part 3;

Bonus;

In the same solution we created before, create a Blazor WASM project and select ‘Individual Accounts’. Just as we did before, copy the Keycloak appsettings section to the new appsettings. In the ‘Program.cs’ file, write these configurations:

Copy the ‘applicationUrl’ from ‘launchSettings’ and register it as a valid redirect URI in the Keycloak client. It’s ready. Annotate the ‘Weather.razor’ page with the ‘[Authorize]’ attribute:

Run the app.

When you click on the ‘Weather’ link, it’ll redirect you to the Keycloak login page, voilá.

As a bonus, we can use a http client to consume the API. For this, we have to create an ‘AuthorizationMessageHandler’ to set the Bearer Token in the http messages:

Register it as transient and as message handler for http client:

In the ‘Weather.razor’ page, inject the ‘IHttpClientFactory’:

And in the code section, call the API to get values from your API:

As the Weather model is the same in the API and Blazor, we don’t have to change it. Now run the API and Blazor, test the weather page, if you check the Network section in you development tools on browser, you can see the Bearer Token.

--

--