Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add custom FTL pages in Keycloak?

I want to add a custom FTL-page to the existing Keycloak pages. Let's call it 'special-number.ftl' that contains a form where you can enter a number and send it to the backend. The submit button should trigger custom java code that I wrote. How do I do this? How do I trigger a custom FTL-page to be shown and trigger some code I wrote with a click on the submit button?

like image 455
Jack Avatar asked Jan 30 '26 10:01

Jack


1 Answers

What you can do is write a Keycloak extension and implement a custom RealmResourceProvider:

To do so start with a RealmResourceProviderFactory

public class CustomRealmResourceProviderFactory implements RealmResourceProviderFactory {

    public static final String ID = "my-custom-pages";

    @Override
    public RealmResourceProvider create(KeycloakSession keycloakSession) {
        return new CustomRealmResourceProvider();
    }

    @Override
    public void init(Config.Scope scope) {

    }

    @Override
    public void postInit(KeycloakSessionFactory keycloakSessionFactory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return ID;
    }
}

And the according RealmResourceProvider:

public class CustomRealmResourceProvider implements RealmResourceProvider {



    @Override
    public Object getResource() {
        return this;
    }

    @Override
    public void close() {

    }

    @GET
    @Path("mypage")
    @Produces(MediaType.TEXT_HTML)
    public Response getSuccessPage() {
        LoginFormsProvider forms = keycloakSession.getProvider(LoginFormsProvider.class);
        return forms.createForm("my-form-template.ftl");
    }


}

Create the freemarker template theme-resources/templates/my-form-template.ftl

<#import "template.ftl" as layout>
<@layout.registrationLayout displayInfo=true; section>
    <#if section = "header">
        ${msg("welcome")}
    <#elseif section = "form">
     CONTENT
    </#if>
</@layout.registrationLayout>

Then add the path of the CustomRealmResourceProviderFactory to the following file in you project: META-INF/services/org.keycloak.services.resource.RealmResourceProviderFactory

Build and add as provider to your keycloak setup. Your endpoints will be available at: /realms/{realmName}/{RealmResourceProviderId}/{path}

In this example: /realms/{realmName}/my-custom-pages/mypage

For more information see: https://www.keycloak.org/docs/latest/server_development/#_extensions_rest

like image 69
Georg Moser Avatar answered Jan 31 '26 23:01

Georg Moser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!