I can't find the way to reproduce the following curl oAuth authentication call in Java:
curl 'https://id.herokuapp.com/oauth/token' -H 'Content-Type: application/x-www-form-urlencoded' -H 'Accept: application/json' -H 'Authorization: Basic AUTH_VALUE' -H 'Connection: keep-alive' --data 'username=_USERNAME&password=_PASSWORD&grant_type=password&scope=read%20write&client_secret=_SECRET&client_id=_CLIENT_ID' --compressed
I don't know how to pass the --data value to the call.
If you're using standard java.net.URL it can be done but the syntax is rather cumbersome, I suggest that you try using HTTP Components library. You should end up with something like this:
final HttpUriRequest request = RequestBuilder.get()
.setUri("https://id.herokuapp.com/oauth/token")
.setHeader("Content-Type", "application/x-www-form-urlencoded")
.setHeader("Accept", "application/json")
.setHeader("Authorization", "Basic AUTH_VALUE")
.addParameter("username", "_USERNAME")
.addParameter("password", "_PASSWORD")
.addParameter("grant_type", "password")
.addParameter("scope", "read write")
.addParameter("client_secret", "_SECRET")
.addParameter("client_id", "_CLIENT_ID")
.build();
final HttpClient client = HttpClientBuilder.create().build();
final HttpResponse response = client.execute(request);
final HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.toString(entity)); // or whatever processing you need
GZip/deflate and keep alive handling is provided out of the box if the HttpClient is created using HttpClientBuilder.
Related
I have api using curl
curl -X PUT "http://localhost:8080/kie-server/services/rest/server/containers/containerid/tasks/210/expiration" -H "accept: application/json" -H "content-type: application/json" -d "{ \"java.util.Date\" : 1540025263987}"
Now I want to call this api using java code :
I am using javax.ws.rs.PUT class for api calling and HttpConnection class.
I have set the requestMethod(POST) and request property.
This is url i am using :
http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration
url = new URL( http://localhost:8080/kie-server/services/rest/server/containers/"+containerId+"/tasks/"+taskId+"/expiration);
conn.setRequestMethod(PUT);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
I want to pass this parameter to api but not sure which method to use ?
{java.util.Date:1534343434"};
This parameter is passed in body.
Can anyone suggest how do I pass this parameter in java rest api ??
I have got a basic curl like below:
curl -X POST \
'https://aogt.pl/auth/' \
-H 'Authorization: Basic NGZjMjExNWQyYTZk' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id=4fc2115'
When I run it in the console on e.g. Ubuntu everything work correctly, I get a good response. Now I would like to map this curl into the java code using okhttp. I write below code:
public class TestMain {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void main(String[] args) throws IOException {
String data = "client_id=4fc2115";
RequestBody body = RequestBody.create(JSON, data);
Request request = new Request.Builder()
.url("https://aogt.pl/auth/")
.addHeader("Authorization", "Basic NGZjMjExNWQyYTZk")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.post(body)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
The pom file look like:
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.0</version>
</dependency>
</dependencies>
The problem is that when I run this code I get "400 Bad Request" so this is problem with server. I wrong map above curl into the java code into the http. Probably the problem is in POST body, because it is not JSON, but what I need to change here, could you please tell me what is wrong? Thank you very much.
The request you want to send has content-type as "application/x-www-form-urlencoded".
So creating the body as a JSON would not work.
You should try forming body in following way:
RequestBody body = new FormBody.Builder().add("client_id", "id_value").build();
RequestBody body = new FormBody.Builder() .add("client_id", "id_value");
Hi hope you had resolved this problem.
Actually, if u want to send a request with 'form-body' instead of 'json', you can easily use this class: 'FormBody'. It inherits RequestBody.
I'm trying to make a POST request using RestTemplate to send a request body and headers.
To do this, I saw that many are using HTTPEntity class. But this class a generic type which needs to be passed. The content type is application/json.
In most cases, I saw that HttpEntity was created with String generic type. Like this:
HttpEntity<String> requestEntity = new HttpEntity<String>(body, headers);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
What I didn't get is, how do I know which data type to use while creating HttpEntity object?
I understood that we do ResponseEntity parse the response from the http call into a string. But I didn't understand the same for http entity.
I tried to create the body in http entity object using google's JsonObject, like this:
JsonObject body = new JsonObject();
body.addProperty("key", "value");
.....
The request when tried in postman works, but didn't work in code using RestTemplate when I used String http entity.
When using JsonObject type, I'm getting this error:
org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Not a JSON Primitive
When using String type http entity, I'm getting some generic error message saying the request isn't valid.
Adding the complete request body :
JsonObject body = new JsonObject();
body.addProperty("transaction_id", transaction_id);
body.addProperty("timestamp", timestamp);
body.addProperty("device_token", deviceToken);
if (forUpdate)
body.addProperty("bit0", true);
The working curl from postman:
curl -X POST \
https://api.devicecheck.apple.com/v1/query_two_bits \
-H 'Content-Type: application/json' \
-H 'authorization: Bearer SOME_BEARER_TOKEN_STRING' \
-H 'cache-control: no-cache' \
-d '{
"device_token": "SOME_DEVICE_TOKEN",
"transaction_id": "f0bc2e5d-5bd9-4437-a455-fd1e210a6268",
"timestamp": 1557073737608
}'
So can someone please help me in understanding how to send this request?
I am having trouble being able to validate a users token with OpenAM. Particularly what type of Agent I should create. Is there anyone that can recommend a solution?
Essentially the REST API will read the users OpenAM tokenid and validate the token with OpenAM which then will return data which contains a username. That username can be used in the REST API method to identify who is accessing the method.
Even more simplified is how can I use a OpenAM token to get the OpenAM user info.
Thanks!
You can use the following endpoints:
Authenticate user:
curl --request POST --header "X-OpenAM-Username: demo" \
--header "X-OpenAM-Password: changeit" \
--header "Content-Type: application/json"
"http://openam.example.com:8080/sso/json/authenticate"
{"tokenId":"AQIC5wM2LY4SfcyTReB5nbrLt3QaH-7GhPuU2-uK2k5tJsA.*AAJTSQACMDEAAlNLABMyOTUxODgxODAwOTE0MTA4NDE3*","successUrl":"/sso/console"}
Validate token:
curl --request POST \
--header "Content-Type: application/json" \
"http://openam.example.com:8080/sso/json/sessions/AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*?_action=validate"
{"valid":true,"uid":"demo","realm":"/"}
Get profile attributes:
curl --request GET \
--header "iPlanetDirectoryPro: AQIC5wM2LY4SfczadxSebQWi9UEyd2ZDnz_io0Pe6NDgMhY.*AAJTSQACMDEAAlNLABM3MTMzMTYwMzM1NjE4NTE4NTMx*" \
"http://openam.example.com:8080/sso/json/users/demo"
{"username":"demo","realm":"/","uid":["demo"],"userPassword":["{SSHA}cIgTNGHWd4t4Ff3SHa6a9pjMyn/Z3e3EOp5mrA=="],"sn":["demo"],"createTimestamp":["20160406210602Z"],"cn":["demo"],"givenName":["demo"],"inetUserStatus":["Active"],"dn":["uid=demo,ou=people,dc=example,dc=com"],"objectClass":["devicePrintProfilesContainer","person","sunIdentityServerLibertyPPService","inetorgperson","sunFederationManagerDataStore","iPlanetPreferences","iplanet-am-auth-configuration-service","organizationalperson","sunFMSAML2NameIdentifier","oathUser","inetuser","forgerock-am-dashboard-service","iplanet-am-managed-person","iplanet-am-user-service","sunAMAuthAccountLockout","top"],"universalid":["id=demo,ou=user,dc=openamcfg,dc=example,dc=com"]}
I ended up going with with idFromSession:
curl --request POST \
--header "iplanetdirectorypro: AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*" \
--header "Content-Type: application/json"
http://openam.example.com:8080/openam/json/users?_action=idFromSession
Then in my java REST API method I used:
String httpsURL = "https://openam.example.com:8080/openam/json/users?_action=idFromSession";
URL url = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
//add request headers
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/json");
// Add session token as header
con.setRequestProperty("iplanetdirectorypro", "AQIC5wM2LY4SfczUFNs-TJwFrCVAKgR0NulIAyNaIkQmjis.*AAJTSQACMDEA
AlNLABQtNTQ3NDE2Njc5ODk4MjYzMzA2MQ..*");
// Send post request
con.setDoOutput(true);
// Read output
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
Based the HTTP POST off of: https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
don't you need cookies to be set ..
Response fieldResponse = given().auth().oauth2( oAuthLogin.getToken())
.config(new RestAssuredConfig().
decoderConfig(
new DecoderConfig("UTF-8")
).encoderConfig(
new EncoderConfig("UTF-8", "UTF-8")
))
.header("iplanetDirectoryPro", oAuthLogin.getToken())
.header("Content-Type", "application/json")
// .contentType("application/json")
.body(myRequest).with()
.when()
.post(dataPostUrl)
.then()
.assertThat()
.log().ifError()
.statusCode(200)
.extract().response();
is failing as bad request 400.Same content header is working in postman.
Only difference i see is cookie.enter image description here
Working as per postman
Not working one which used restassured framework enter image description here
I know I can add http parameters using the setParameter method, but how do I pass a body to the http request using the URIBuilder class?
For example, this
URI uri = new URIBuilder().setScheme("http")
.setHost("localhost:9091/test").setParameter("a", "1")
.setParameter("b", "2").build();
is equivalent to the following curl request:
curl -X POST http://localhost:9091/test\?a\=1\&b\=2
but how do I build a URL using URIBuilder (or any other class) for the following curl:
curl -X POST http://localhost:9091/test -d '{"a":1,"b":2}'
HttpUriRequest request = RequestBuilder.create("POST")
.setUri("http://localhost:9091/test")
.setEntity(new StringEntity("{\"a\":1,\"b\":2}", ContentType.APPLICATION_JSON))
.build();