Skip to content

Instantly share code, notes, and snippets.

@raviyasas
Last active May 7, 2020 18:35
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/141f100b8c5d9bd806085b1d6358d8f4 to your computer and use it in GitHub Desktop.
Save raviyasas/141f100b8c5d9bd806085b1d6358d8f4 to your computer and use it in GitHub Desktop.
Keycloak admin REST APIs - Check username
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class CheckUsername {
public static void main(String args[]) throws IOException {
new CheckUsername().checkUsername("user1");
}
public Boolean checkUsername(String username) throws IOException {
String port = "8081";
String realm = "api";
String server = "localhost";
String content_type = "application/json";
String method_type = "GET";
String encode_type = "UTF-8";
String bearerToken = new GetToken().getBearerToken();
URL url = new URL("http://" + server + ":" + port + "/auth/admin/realms/" + realm + "/users?username=" + username);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(method_type);
conn.setRequestProperty("Content-Type", content_type);
conn.setRequestProperty("Authorization", "Bearer " + bearerToken.trim());
conn.setDoOutput(true);
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();
if(response.contentEquals("[]")){
return false;
}else {
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment