Keycloak tutorial for beginners

Keycloak is an Identity and Access Management Server for Modern Applications and Services. In this Keycloak tutorial we will learn how to set up Keycloak and configure it to authenticate/authorize Enterprise applications.

First of all, download the latest stable build of Keycloak from http://keycloak.jboss.org/keycloak/downloads

Then, you will need to patch our WildFly server in order to enable the keycloak subsystem, so download as well the keycloak adapter from https://www.keycloak.org/downloads.html

Starting Keycloak

Keycloak ships bundled in a WildFly installation. We will start it with an offset of 100 in order to avoid conflicts with our WildFly server (that will be bound with 0 offset), where our application will run:

$ ./standalone.sh -Djboss.socket.binding.port-offset=100

Next, log into Keycloak Administration Console, available at: http://localhost:8180

In your first Login, you will be requested to create an administration user:

Next, login with the admin user you have just created:

Create your Realm, Roles and Users

The core concept in Keycloak is a Realm. A realm secures and manages security metadata for a set of users, applications, and registered oauth clients. Users can be created within a specific realm within the Administration console. Roles (permission types) can be defined at the realm level and you can also set up user role mappings to assign these permissions to specific users.

First, create a new Realm by clicking on the Add Realm Button, located on the left side bar:

Next, enter the Realm Name, for example MyRealm and click on Create:

Then, we will define a Role. The Role will be used by your applications to define which users will be authorized to access the application. Click on the “Roles” left link and choose “Add Role“:

We have added a Role named “Manager” that will be authorized to access our application. So far we don’t have any User, besides the admin user. We will create another one to be used by our application. Click on the “Users” left option and choose to Add a new User:

The User named “frank” will be added by clicking on Save. Now select the User from the list: we need to perform two actions on it.

The first one will be setting a password for it so click on Credentials and set a new Password for the user:

Finally, we will include the User as part of the Manager Role. Click on Role Mappings and assign the User to the Manager Role by selecting the Manager Role and clicking on Add selected:

Define secure Client policies

Done with User and Realms. We need to define which applications are mapped to our Users/Roles. In the earlier versions of KeyCloak you had to click on the “Applications” left link. Now applications are categorized as “Clients” so click on that link on the left:

Choose to Create a new Client. The most important settings are the application Root URL (that will be appended to the URI path) and the Redirect URIs where request will be forwarded after login. In our case, we will create a web application named “keydemo” therefore we will use the following settings:

Next, click on Save. Once saved, the last step will be generating a public key for your realm that will be bundled in your application. From the Clients perspective, click on the Installation link and choose to generate a JSON authorization code for your application:

Download the JSON or simply copy it in an editor, we will use it in a minute.

Installing Keycloak adapter for WildFly

Your application server, as it is, is now aware of Keycloak authentication/authorization mechanisms, hence we need to install an adapter for it. You should have already download the correct installer for your server version. In order to patch the application server perform these two steps:

1) Unzip the Adapter into the directory where you have installed WildFly:

Unzip this file into the root directory of your Wildfly distribution.

2) Next execute the CLI script to install the adapter:
For WildFly 10:

$ cd bin
$ ./jboss-cli.sh --file=adapter-install-offline.cli

For WildFly 11 and above:

$ cd bin
$ ./jboss-cli.sh --file=adapter-elytron-install-offline.cli

This script will make the appropriate edits to the …​/standalone/configuration/standalone.xml file of your app server distribution.

Great. Reload or Restart your server which now is Keycloak aware!

Securing applications with Keycloak

This paragraph of our Keycloak tutorial discusses how to secure applications. There are three options to authenticate your applications using Keycloak.

  • The first option consists in adding the Keycloak JSON file within your Web application and specify in web.xml that we will be using KEYCLOAK Auth.
  • The second option consists in configuring WildFly keycloak’s subsystem with the list of applications that will use KEYCLOAK Auth.
  • The third option allows to download the CLI command to run on WildFly to allow Keycloak Authentication/Authorization for a specific deployment unit.

Keycloak security in the Web application

Create a Web application that exposes the “/hello” URL and include within the web.xml file a security-constraint bound to the “Manager” Role. Also include as authentication mechanism “KEYCLOAK” which is not a standard JEE authentication mechanism, hence it needs that you patched the application server as we have describer earlier:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <module-name>basicauth</module-name>
	
    <security-constraint>
        <web-resource-collection>
            <url-pattern>/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>Manager</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>KEYCLOAK</auth-method>
        <realm-name>MyRealm</realm-name>
    </login-config>

    <security-role>
        <role-name>Manager</role-name>
    </security-role>
</web-app>

Next, we need to add, in the WEB-INF folder, is a keycloak.json with that contains the JSON descriptor we have just generated:

{
   "realm":"MyRealm",
   "auth-server-url":"http://localhost:8180/auth",
   "ssl-required":"external",
   "resource":"demo-keycloak",
   "credentials":{
      "secret":"86f1644f-b686-4011-8c05-31ca7245f94a"
   },
   "confidential-port":0
}

Save and deploy the application. If you try to access your application at localhost:8080/hello the Keycloak login authentication UI will prompt:

Enter your User’s credentials with the “Manager” Role and verify that you can access the pages contained in your application.

Plugging Keycloak security in the WildFly (XML)

This option has the advantage that can be applied without changing the content of your Web application. It requires accessing the XML Configuration of your WildFly Application Server.

From the Keycloak Clients Panel, select the Installation Tab and pickup in the Format OptionKeycloak OIDC JBoss Subsystem XML” as you can see from this picture:

Next, copy the XML template from the Installation page, and paste this into the standalone.xml file that resides in the standalone/configuration directory of the application server instance on which your application is deployed.

Open the standalone/configuration/standalone.xml file (or the one you use) and search for the following text:

<subsystem xmlns="urn:jboss:domain:keycloak:1.1"/>

Simply paste the XML in the subsystem and replace the secure-deployment name with the application name. You are done!

Plugging Keycloak security in the WildFly (CLI)

Finally, the last option which you can use, is available in the Format OptionKeycloak OIDC JBoss Subsystem CLI” as you can see from this picture:

This option is the recommended choice. A common use case for it is creating a MicroService with WildFly Bootable Jar, where your server configuration includes custom CLI commands to run at start.

Some example applications

Well, done. You have just completed your first Keycloak tutorial. We have several examples of Application Secured with Keycloak.

If you want to check a JAX-RS application secured with Keycloak (WildFly) then check this tutorial: Keycloak OAUTH2 example with a REST Application

If you want to check a JAX-RS application secured with Keycloak (Spring Boot) then check this tutorial: Managing Keycloak user metadata and custom attributes