ASP.Net Core & Angular OpenID Connect using Keycloak

How to setup user’s authentication for an ASP.Net Core web API and an Angular front end using Keycloak server for user federation and OpenID Connect.

Keycloak

Keycloak is an open source identity provider owned by Red Hat. It allows to easily add authentication to any application and offers very interesting features such as user federation, identity brokering and social login. In the .Net ecosystem, one of its “competitor” would be Identity Server or OpenIddict with Asp.Net Identity.

The main difference between Keycloak and the two other mentioned solution is that it’s a standalone product and not a library. This means that it can run “on its own”. It’s good if you have an ecosystem of application (maybe built with different technologies) and don’t want to make one of the application the “master” that does all the user management. It’s also a bit more complete, with a fully fledged management user interface and support for multi tenancy.

My goal in this article is to describe how to install a simple instance of Keycloak, secure the API side of an application developed with ASP.Net Core WebApi and secure an Angular client side application that will use the WebApi as a backend.

Enough talking, let’s get started

Installing Keycloak

Keycloak has been built with Java on top of the Wildfly application server. There is a quite long installation procedure described in the documentation. In our case, we want to have a simple test server to be able to develop our sample application and will do so using Docker.

I won’t explain here how to install docker, it’s pretty straightforward, head to the docker homepage if you need guidance. I’ll just assume you already have docker installed on your machine and it’s working correctly.

There are quite a few docker images available on Docker Hub. We’re going to get the official “standard” package that is basically a ready to use Keycloak installation, complete with the database and everything. You can pass a couple of environment variables to directly create the admin account because none is created by default.

Remark: I wouldn’t recommend using that installation of Keycloak in production as there is no redundancy and no backup of the data. I would recommend that you read on Keycloak’s high availability setup on the official documentation.

docker run --name keycloak -p 8080:8080 -e KEYCLOAK_USER=<USERNAME> -e KEYCLOAK_PASSWORD=<PASSWORD> jboss/keycloak

This will attach Keycloak to the port 8080 of the host machine. Once the machine has started, open your browser and go to localhost:8080. It should display Keycloak’s landing page.

Keycloak’s default landing page

Click the Administration Console link and connect using the username and password combination that you have set in the Docker run command. You should now see Keycloak’s administration page.