Created
July 18, 2017 13:14
-
-
Save thomasdarimont/c59c14f45ea2ee00d7b6fbe2c013c5f1 to your computer and use it in GitHub Desktop.
Keycloak authentication with extended keycloak-installed adapter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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