Demonstration of using Keycloak for authentication of a Blazor Server App
Install Keycloak using the instructions from the Keycloak web site. This document assumes you've done all steps from the quick start tutorial, including:
- Keycloak installed and started
- New realm created, named
myrealm
- New user created, named
myuser
Create a new client named my-blazor-server-app
in the realm named "myrealm".
- Open the Keycloak Admin Console
- If not already selected, select "myrealm"
- Click 'Clients'
- Fill in the form with the following values:
- Client ID:
my-blazor-server-app
- Client Protocol:
openid-connect
- Root URL:
https://localhost:44322/
- Client ID:
- Click
Save
- Set the new client's access type to "confidential"
- Click
Save
. After this, a new tab "Credentials" will be visible.
- Open the 'Credentials' tab and make sure "Client id and secret" is set the 'Client authenticator'. Also note the secret - this will be used in our blazor application that is being secured.
Keycloak has two types of user roles:
- realm roles (shared accross all client applications in a realm) and
- client roles (specific for a client application)
- Edit the newly created client application and select the 'Roles' tab.
- Add two roles to the
my-blazor-server-app
:blazor-admin
blazor-operator
- Assign the
blazor-operator
role to themyuser
user account.
This is an important step. By default user roles are not included in the user profile. This demo sample is reading the user roles from the user profile, so we must make sure user roles are included in the user profile.
- Include client roles in the user profile
- Open the BlazorAuthSample.sln using Visual Studio 2019 (this is .net core 5.0 application).
- Configure client id and secret in the appsettings.json (see step 8 in the Keycloak install and configure section).
- Run the application
If you try to access the counter or fetch data menu, the application will redirect you to Keycloak login.
If you log in with myuser
, you should be able to access weather data, but counter will not be available because it requires the blazor-admin
role.
All the required changes needed to enable Keycloak authentication on a vanilla Blazor Server application are in a single commit.