Keycloak OpenID Authentication with WildFly

Keycloak is an open-source identity and access management solution that supports OpenID Connect and OAuth 2.0 protocols. In this tutorial we will learn how to configure a Keycloak Realm and use as OpenID Client an application running on WildFly.

Before we get started, we need to learn some terms we will use in this article:

  • OAuth is a protocol that enables applications to access resources on behalf of a user. It works by having the user authorize a third-party application to access their resources, such as their social media profile, without sharing their login credentials.
  • On the other hand, OpenID Connect is an authentication protocol that builds on top of OAuth 2.0 to enable user authentication. It provides a standardized way for users to authenticate with an identity provider (IdP) and then receive an ID token, which can be used to access protected resources.

In this tutorial we will show how to use OpenID Connect to authenticate an application through a Realm that is available on Keycloak Identity Manager.

In order to run this example, you will need a Keycloak server up and running. To learn more about it, check this tutorial: Introduction to Keycloak

Then, we will start Keycloak on port 8180 to avoid conflicts with WildFly:

./kc.sh start-dev --http-port=8180

Step1: Create a Keycloak Realm

Our example requires a Keycloak Realm to be set up and a Client definition which is allows up to be authorized using a Token issued by Keycloak. You can create the Realm and Client by executing the following CLI, which uses Keycloak Admin CLI (located in the bin folder):

#Authenticate with the Admin Server    
./kcadm.sh config credentials --server http://localhost:8180 --realm master --user admin --password admin

#Create Realm Demo-Realm ./kcadm.sh create realms -s realm=demo-realm -s enabled=true -o
#Create User customer-admin ./kcadm.sh create users -r demo-realm -s username=customer-admin -s enabled=true -s email="[email protected]"
#Set customer-admin password ./kcadm.sh set-password -r demo-realm --username customer-admin --new-password admin
#Create Client ./kcadm.sh create clients -r demo-realm -s clientId=customer-manager-client -s bearerOnly="false" -s "redirectUris=[\"http://localhost:8080/*\"]" -s enabled=true -s directAccessGrantsEnabled=true -s clientAuthenticatorType=client-secret -s secret=mysecret
#Create Role customer-manager ./kcadm.sh create roles -r demo-realm -s name=customer-manager
#Assign Role to customer-admin ./kcadm.sh add-roles --uusername customer-admin --rolename customer-manager -r demo-realm

You can check from Keycloak’s Admin Console that the Realm and Client have been correctly defined:

keycloak oauth2 tutorial wildfly keycloak oauth2 tutorial wildfly keycloak oauth2 tutorial wildfly

As you can see, we have defined as Redirect URI a generic localhost:8080 which will return, after checking the token, to the root page of a Web Server. In real world examples, you will want to redirect to a precise Web context.

Before leaving the KeyCloak Admin UI, download the oidc.json file for your Client which contains the coordinates for the auth server, the Client name and secret and the realm:

{
  "realm": "demo-realm",
  "auth-server-url": "http://localhost:8180/",
  "ssl-required": "external",
  "resource": "customer-manager-client",
  "credentials": {
    "secret": "mysecret"
  },
  "confidential-port": 0
}

Building the OpenID Client Example

This project will run as WildFly Bootable Jar. To learn more about WildFly bootable Jar we recommend checking this tutorial: Turn your WildFly applications in bootable JARs

Our application contains only a Servlet Class which is secured with the “customer-manager” Role:.

@WebServlet("/secured")
@ServletSecurity(httpMethodConstraints = { @HttpMethodConstraint(value = "GET", rolesAllowed = { "customer-manager" }) })
public class SecuredServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Principal user = req.getUserPrincipal();

        try (PrintWriter writer = resp.getWriter()) {
            writer.println("Welcome user: "+user);
        }
    }

}

Since WildFly 25 there is native support for OIDC Client Authentication therefore you don’t need to add any Keycloak adapter to your application. Just include in your web.xml OIDC as authentication method:

<web-app version="2.5" 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_2_5.xsd"
   metadata-complete="false">

    <login-config>
        <auth-method>OIDC</auth-method>
    </login-config>

</web-app>

Finish the configuration by including the oidc.json file in the WEB-INF folder of your application:

Here is how your application looks like before we build it:

keycloak oidc example

Configuring WildFly Bootable Jar with OIDC Support

To build your application as Bootable Jar you need to include the wildfly-jar-maven-plugin plugin in your Maven build section. Within it, include the elytron-oidc-client layer in addition to the web-server layer:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-jar-maven-plugin</artifactId>
    <version>8.1.0.Final</version>
    <configuration>
        <feature-packs>
            <feature-pack>
                <location>wildfly@maven(org.jboss.universe:community-universe)#${version.wildfly}</location>
            </feature-pack>
        </feature-packs>
        <layers>
            <layer>web-server</layer>
            <layer>elytron-oidc-client</layer>
        </layers>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>package</goal>
            </goals>
        </execution>
    </executions>
</plugin>

You can start the application as follows:

mvn clean install wildfly-jar:run

Testing from the Browser

If you are testing the Endpoint from the browser, just head to: http://localhost:8080/secured
You will be redirected to Keycloak Login Page:

Enter “customer-admin” / “admin” as User and Password. You will get as response the User id which contains the Role “customer-admin”
keycloak demo OIDC

Conclusion

This article was a walk though the configuration of a KeyCloak Realm and the creation of an OpenID Client which authenticates to the keycloak Realm.

Source code available here: https://github.com/fmarchioni/mastertheboss/tree/master/keycloak/oauth2

Found the article helpful? if so please follow us on Socials