Search code examples
javaoauth-2.0keycloakapache-httpclient-4.xbearer-token

HttpClient post to obtain a Bearer token from keycloak


I have set up a keycloak 11.0.2 in standalone mode. It is up and running fine. I am able to create a POST-Request with Postman to obtain a bearer token. Now I want to obtain a token from the keycloak server with the Apache HttpClient. I don't know how to do it.

This is my code, but it returns 400 error, and i had 415 as well:

            CloseableHttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://localhost:8180/auth/realms/Demo-Realm/protocol/openid-connect/token");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("grant_type","password");
            httpPost.addHeader("client_secret","30e8ebdf-7fbb-449d-9d94-709166b879b0");
            httpPost.addHeader("client_id","springboot-microservice");
            httpPost.addHeader("username","employee1");
            httpPost.addHeader("password","mypassword");
            CloseableHttpResponse response = client.execute(httpPost);
            System.out.println("response: " + response.toString());
            client.close();

This is the response:

response: HttpResponseProxy{HTTP/1.1 400 Bad Request [Cache-Control: no-store, X-XSS-Protection: 1; mode=block, Pragma: no-cache, X-Frame-Options: SAMEORIGIN, Referrer-Policy: no-referrer, Date: Tue, 17 Nov 2020 14:31:31 GMT, Connection: keep-alive, Strict-Transport-Security: max-age=31536000; includeSubDomains, X-Content-Type-Options: nosniff, Content-Type: application/json, Content-Length: 84] ResponseEntityProxy{[Content-Type: application/json,Content-Length: 84,Chunked: false]}}

I wonder how to do it right. I try to do it like Postman does it, but I am missing something

UPDATE / Edit: Now I am a step further, but i still can not understand the behaviour. Here is my Code:

      String result = "";
            HttpPost post = new HttpPost("http://localhost:8180/auth/realms/Demo-Realm/protocol/openid-connect/token");
            post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            StringBuilder json = new StringBuilder();
            json.append("{");
            json.append("\"grant_type\":\"password\"");
            json.append("\"client_id\":\"springboot-microservice\",");
            json.append("\"username\":\"employee1\"");
            json.append("\"password\":\"mypassword\"");
            json.append("}");
            post.setEntity(new StringEntity(json.toString()));
            try (CloseableHttpClient httpClient = HttpClients.createDefault();
                 CloseableHttpResponse response = httpClient.execute(post)) {
                result = EntityUtils.toString(response.getEntity());
            }
            System.out.println("result: " + result.toString());

Now i am getting as response:

result: {"error":"invalid_request","error_description":"Missing form parameter: grant_type"}

But this is what i did sent? What am I doing wrong?


Solution

  • Can you try with this BasicNameValuePair instead of sending as a json:

    ArrayList<NameValuePair> parameters;
    parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("grant_type", "password"));
    parameters.add(new BasicNameValuePair("client_id", "springboot-microservice"));
    parameters.add(new BasicNameValuePair("username", "employee1"));
    parameters.add(new BasicNameValuePair("password", "mypassword"));
    parameters.add(new BasicNameValuePair("client_secret", "30e8ebdf-7fbb-449d-9d94-709166b879b0"));
    post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));