Java Spring, a popular framework for building enterprise-level applications, can seamlessly integrate with Keycloak, a robust open-source Identity and Access Management (IAM) solution. This combination offers a powerful way to implement secure authentication, authorization, and user management features in your Spring-based applications. Let’s explore how to achieve this integration along with key functionalities.

Understanding OAuth2

At the heart of Keycloak’s integration lies the OAuth2 protocol. This protocol enables secure authorization and delegation of access between applications. In essence, your Spring application acts as a client that requests authorization from Keycloak (the authorization server) on behalf of the user. Keycloak then issues an access token that your Spring application can use to access protected resources on behalf of the authenticated user.

Role Manager

Keycloak’s role management system allows you to define various roles within your application and assign them to users. You can then use these roles within your Spring application to control access to different parts of your application or specific functionalities. This provides a fine-grained authorization mechanism.

MFA (Multi-Factor Authentication)

Keycloak supports MFA, which adds an extra layer of security to your application. Users will be required to provide additional verification, such as a code from their smartphone or a fingerprint scan, in addition to their username and password.

Email Verification and Reset

Keycloak provides built-in functionality for email verification and password reset. When a user registers, they receive an email with a link to verify their email address. Similarly, if they forget their password, they can request a password reset link to be sent to their registered email address.

Customizing the Login Screen

Keycloak offers a good degree of flexibility when it comes to tailoring the login experience to match your application’s branding and design. Here’s a breakdown of the steps involved:

  1. Access the Keycloak Themes:

    • Log in to your Keycloak Admin Console.
    • Navigate to your realm.
    • Go to Realm Settings -> Themes.
  2. Create a New Theme or Copy an Existing One

    • You have two options here:
      • Create a New Theme: Click the Add Theme button and provide a name for your new theme.
      • Copy an Existing Theme: If you want to make modifications to the default look, you can copy the base theme and then customize it.
  3. Modify the Theme Files:

    • Once you’ve created or copied a theme, you’ll see a list of files associated with it. The most important one for login customization is login/login.ftl.
    • Download this login.ftl file.
    • Open the file in a text editor or your preferred IDE.
    • You’ll see a mix of HTML, CSS, and FreeMarker template language constructs. This is where you can make your changes.
  4. Key Areas for Customization

    • HTML Structure: Modify the existing HTML elements or add new ones to change the layout of the login form.
    • CSS Styling: Update the CSS rules to adjust colors, fonts, spacing, and other visual aspects of the login screen.
    • FreeMarker: Use FreeMarker directives to dynamically include content or control the display of elements based on conditions.
    • Keycloak-Specific Classes: Keycloak provides some CSS classes that you can leverage to target specific elements on the login screen. Refer to the Keycloak documentation for a list of these classes.
  5. Upload the Modified Theme:

    • Once you’re satisfied with your changes, save the login.ftl file.
    • Back in the Keycloak Admin Console, in your theme’s file list, click the Upload button next to login/login.ftl.
    • Select your modified file and upload it.
  6. Apply the Theme to your Client

    • Navigate to your client’s settings.
    • Go to the Themes tab.
    • Under Login Theme, select the name of your custom theme.
    • Save the changes.

Tips for Customization

  • Inspect Element: Use your browser’s developer tools to inspect the elements on the default login screen. This will help you understand the existing structure and CSS classes.
  • Keycloak Documentation: Refer to the Keycloak documentation for detailed information about theming and customization options.
  • Version Compatibility: Keep in mind that the theming structure and available options might vary slightly between different Keycloak versions.
  • Testing: Thoroughly test your customized login screen across different browsers and devices to ensure it looks and functions as expected.

Advanced Customization

  • If you require even more extensive customization, you can explore creating custom FreeMarker templates or even developing your own custom login forms.

Spring Configuration

Let’s delve into the essential steps to configure Keycloak in your Spring application.

  1. Add Keycloak Dependencies: Include the necessary Keycloak dependencies in your pom.xml (for Maven) or build.gradle (for Gradle) file.

    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-spring-boot-starter</artifactId>
        <version>x.x.x</version> </dependency>
    
  2. Configure Keycloak Properties: Provide your Keycloak server details, realm name, client ID, and other relevant settings in your application.properties or application.yml file.

    keycloak:
      realm: your-realm-name
      auth-server-url: http://localhost:8080/auth
      ssl-required: external
      resource: your-client-id
      public-client: true
      bearer-only: true
    
  3. Secure Endpoints: Use Spring Security annotations to protect your endpoints based on roles or other authorization criteria.

    @PreAuthorize("hasRole('admin')")
    @GetMapping("/admin")
    public String adminPage() {
        return "Admin Page";
    }
    
  4. Access User Information: Retrieve user information, including roles and attributes, from the Keycloak Principal object in your controllers.

    @GetMapping("/user")
    public String userPage(Principal principal) {
        KeycloakPrincipal keycloakPrincipal = (KeycloakPrincipal) principal;
        KeycloakSecurityContext keycloakSecurityContext = keycloakPrincipal.getKeycloakSecurityContext();
        AccessToken accessToken = keycloakSecurityContext.getToken();
        // Access user information from accessToken
        return "User Page";
    }
    

Integrating Java Spring with Keycloak offers a robust and flexible solution for implementing authentication, authorization, and user management in your applications. By leveraging OAuth2, role management, MFA, and other Keycloak features, you can enhance the security and user experience of your Spring-based applications. Remember that this blog post provides a foundational overview. Delve deeper into the official Keycloak and Spring Security documentation for more advanced configurations and customization options.


Discover more from GhostProgrammer - Jeff Miller

Subscribe to get the latest posts sent to your email.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.