Skip to content

Instantly share code, notes, and snippets.

@raviyasas
Created May 7, 2020 18:37
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 raviyasas/afb17b63b3805c7f3906dc2514d20c15 to your computer and use it in GitHub Desktop.
Save raviyasas/afb17b63b3805c7f3906dc2514d20c15 to your computer and use it in GitHub Desktop.
Keycloak REST APIs - Get bearer token
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
public class GetToken {
public static void main(String[] args) throws IOException {
new GetToken().getBearerToken();
}
public String getBearerToken() throws IOException{
String client_id = "login-app";
String grant_type = "client_credentials";
String client_secret = "6b574a0b-6624-4d7a-9ac6-485c1fdcc9e0";
String port = "8081";
String realm = "api";
String server = "localhost";
String content_type = "application/x-www-form-urlencoded";
String method_type = "POST";
String encode_type = "UTF-8";
URL url = new URL("http://"+ server +":"+ port +"/auth/realms/"+ realm +"/protocol/openid-connect/token");
Map params = new LinkedHashMap();
params.put("client_id", client_id);
params.put("grant_type", grant_type);
params.put("client_secret", client_secret);
StringBuilder postData = new StringBuilder();
for(Map.Entry param : params.entrySet()){
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), encode_type));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), encode_type));
}
byte[] postDataBytes = postData.toString().getBytes(encode_type);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(method_type);
conn.setRequestProperty("Content-Type", content_type);
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), encode_type));
String line;
StringBuilder result = new StringBuilder();
while ((line = in.readLine()) != null) {
result.append(line);
}
String response = result.toString();
String[] array = response.split(",");
String[] accessToken = array[0].split(":");
String token = accessToken[1].replace("\"","");
System.out.println(token);
return token;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment