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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With