Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hendrikebbers/4c14db0967ce14ce623baa1f698b230c to your computer and use it in GitHub Desktop.
Save hendrikebbers/4c14db0967ce14ce623baa1f698b230c to your computer and use it in GitHub Desktop.
Keycloak Java login
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