Created
January 4, 2018 06:54
-
-
Save hendrikebbers/4c14db0967ce14ce623baa1f698b230c to your computer and use it in GitHub Desktop.
Keycloak Java login
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
final String content = "client_id=" + appName + "&username=" + user + "&password=" + password + "&grant_type=password" | |
final byte[] rawContent = content.getBytes(PlatformConstants.CHARSET); | |
final URI url = new URI(authEndpoint + "/auth/realms/" + realmName + "/protocol/openid-connect/token"); | |
final HttpURLConnection connection = new DefaultHttpURLConnectionFactory().create(url); | |
connection.setRequestMethod(RequestMethod.POST.getRawName()); | |
connection.setRequestProperty("charset", "UTF-8"); | |
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); | |
connection.setRequestProperty("Content-Length", rawContent.length + ""); | |
connection.setDoOutput(true); | |
connection.setDoInput(true); | |
try { | |
final OutputStream w = connection.getOutputStream(); | |
w.write(rawContent); | |
w.close(); | |
} catch (IOException e) { | |
throw new DolphinRuntimeException("Looks like the security server is not reachable", e); | |
} | |
final int responseCode = connection.getResponseCode(); | |
if(responseCode == 401) { | |
throw new DolphinRuntimeException("Invalid login!"); | |
} | |
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); | |
try { | |
final InputStream is = connection.getInputStream(); | |
int read = is.read(); | |
while (read != -1) { | |
byteArrayOutputStream.write(read); | |
read = is.read(); | |
} | |
} catch (FileNotFoundException e) { | |
throw new DolphinRuntimeException("Maybe the realm or application is not defined in the keycloak server", e); | |
} | |
final byte[] rawInput = byteArrayOutputStream.toByteArray(); | |
final String input = new String(rawInput); | |
final Gson gson = PlatformClient.getService(Gson.class); | |
final KeycloakOpenidConnectResult result = gson.fromJson(input, KeycloakOpenidConnectResult.class); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment