Skip to content

Instantly share code, notes, and snippets.

@K0NRAD
Created April 8, 2019 15:40
Show Gist options
  • Save K0NRAD/0b9b293db31b063587fc65fff9126f15 to your computer and use it in GitHub Desktop.
Save K0NRAD/0b9b293db31b063587fc65fff9126f15 to your computer and use it in GitHub Desktop.
keycloak admin api insecure call with unirest
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.junit.Test;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import static org.assertj.core.api.Assertions.assertThat;
public class UnirestAdminApiKeycloakTest {
@Test
public void getAccessToken() throws Exception {
Unirest.setHttpClient(insecureHttpClient());
HttpResponse<JsonNode> response = Unirest.post("https://signin.com/auth/realms/master/protocol/openid-connect/token")
.header("Content-Type", "application/x-www-form-urlencoded")
.header("Accept", "application/json")
.header("cache-control", "no-cache")
.body("client_id=admin-cli&username=admin&password=admin&grant_type=password")
.asObject(JsonNode.class);
String json = response.getBody().toString();
assertThat(json).contains("access_token");
String token = response.getBody().getObject().getString("access_token");
assertThat(token).isNotNull();
}
private CloseableHttpClient insecureHttpClient() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
return HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment