Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Keycloak authentication with extended keycloak-installed adapter
package demo;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.keycloak.adapters.installed.KeycloakInstalled;
import org.keycloak.representations.AccessToken;
public class SimpleDesktopApp {
public static void main(String[] args) throws Exception {
int timeoutSeconds = 20;
KeycloakInstalled keycloak = new KeycloakInstalled();
keycloak.setLocale(Locale.GERMAN);
keycloak.setHttpResponseWriter((pw, kc) -> {
pw.println("HTTP/1.1 200 OK");
pw.println();
switch (kc.getLoginStatus()) {
case LOGGED_IN:
pw.println("<html><h1>Login complete.</h1>"
+ "<div>Please <a href=\"#\" onclick=\"close_window();return false;\">close</a> this browser tab.</div></html>");
break;
case LOGGED_OUT:
pw.println("<html><h1>Logout complete.</h1>"
+ "<div>Please <a href=\"#\" onclick=\"close_window();return false;\">close</a> this browser tab.</div></html>");
break;
default:
// ignore
}
});
keycloak.loginDesktop();
AccessToken token = keycloak.getToken();
Executors.newSingleThreadExecutor().submit(() -> {
System.out.println("Logged in...");
System.out.println("Token: " + token.getSubject());
System.out.println("Username: " + token.getPreferredUsername());
try {
System.out.println("AccessToken: " + keycloak.getTokenString());
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.printf("Logging out in...%d Seconds%n", timeoutSeconds);
try {
TimeUnit.SECONDS.sleep(timeoutSeconds);
} catch (Exception e) {
e.printStackTrace();
}
try {
keycloak.logout();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Exiting...");
System.exit(0);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.