I want to send a post request which has a bearer authorization required in java. The body of the post request takes parameters of in the following json format in postman:
{
"name": "project-002",
"description": "Test number 2",
"users": [
"ppallavalli#umass.edu"
]
}
I want to send a post request in the following way by which i executed my get request which needed authorization because authorization easier this way.
HttpUriRequest httpGet = RequestBuilder.get().setUri("https://sandbox.predera.com/aiq/api/projects/a-443018111").setHeader(HttpHeaders.AUTHORIZATION,authHeader).build();
In specific i want to send a post request using HttpUriRequest and RequestBuilder.post because authorization is easier in this case especially because the authorization required in my case is a Bearer token. Also, in the above request execution, auth header is string i have already initialized to a Bearer authorization token
You can use RequestBuilder.post() to build a POST request with a StringEntity to pass your JSON String. Rest of the headers including Authorization etc. should remain same.
String url = "https://sandbox.predera.com/aiq/api/projects/a-443018111";
String jsonString = "{...}";
HttpUriRequest httpPost = RequestBuilder.post(url).setHeader(HttpHeaders.CONTENT_TYPE, "application/json").addHeader(HttpHeaders.AUTHORIZATION, authHeader).setEntity(new StringEntity(jsonString)).build();
...
Related
I am trying to setup code in such as way that executes a POST request in my step definition class, and the POST request includes authorization (bearer token), content type, and Cookies in headers, as well as a request body in json format.
I have the bearer token process setup and am using the bearerToken for the authorization as header, content type is application/json, and the request body has the below structure:
I am unsure how to proceed in this way using Rest Assured. Below is a given method that sets the base uri and the bearer token based on environment, and based on that the bearer token will be used accordingly for authorization as header when executing the POST request:
#Given("Request the environment for the Master API {string}")
public void getMasterAPIBaseUrl(String region) throws JSONException {
if (region.equalsIgnoreCase("DEV")) {
bearerToken = accTokenSetup.accessTokenSetup(region);
RestAssured.baseURI = urlProps.getProperty("devMasterAPIUrl");
}
else if (region.equalsIgnoreCase("STG")) {
bearerToken = accTokenSetup.accessTokenSetup(region);
RestAssured.baseURI = urlProps.getProperty("stgMasterAPIUrl");
}
Reporter.log("Getting master api base url for the environment which is " + RestAssured.baseURI, true);
}
Now I need an #When step that will execute the mentioned POST request with the request body and the headers (authorization, content-type, and Cookies). I know what is required would be the endpoint, headers, request body, etc. but unsure of how to proceed with it. Any help would be appreciated!
I'm trying to get token access (protocol oauth2) to dynamics 365.
That's the code that build and execute the http post request:
URI uri = new URIBuilder()
.setScheme("https")
.setHost("login.microsoftonline.com")
.setPath("/"+PropertyUtils.getInstance().getProperty("AD_TENANT_ID")+"/oauth2/token")
.setParameter("grant_type", "client_credentials")
.setParameter("client_id", PropertyUtils.getInstance().getProperty("CLIENT_ID"))
.setParameter("resource", PropertyUtils.getInstance().getProperty("RESOURCE"))
.setParameter("client_secret", PropertyUtils.getInstance().getProperty("CLIENT_SECRET"))
.build();
HttpPost post = new HttpPost(uri);
HttpResponse response = client.execute(post);
the response json is:
{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: 'grant_type'.\r ...
why response tell me that grant_type is missing when it's in the request as a parameter?
You are trying to perform the request putting those parameters in the URI as query parameters. Although those parameters needs to be put in the body of the request as form url encoded.
{"Content-Type": "application/x-www-form-urlencoded"}
Question
When using the Google Plus Sign In Api with the Play Framework do you have to set headers in a different way? Is there something I am doing wrong here?
Background
I am using Play Framework(in Java) to use the Google Plus Sign in Api.
I am running into issues on the second leg of OAuth authentication, exchanging the Authorization Code for a Token.
Basic OAuth Flow
Pretty Picture
Redirect user to User login/Consent screen
This asks the user if they want to grant you application permission to the requested scopes
URL: https://accounts.google.com/o/oauth2/auth
Exchange Authorization Code for a Token
If the user gives your application permission then they will be redirected to a URL you specify, in that URL(As a GET param) will be an Authorization Code.
Your application can then use this Authoriztion Code to get a Token from the server
Your application does this by making a HTTP request to a endpoint on the Google Servers(Or whatever service you are using)
URL: https://accounts.google.com/o/oauth2/token
Use Token in API requests
The Issue
To Exchange the Authorization Code for a Token, with the Google Plus Sign In Api, you must make a POST request to https://accounts.google.com/o/oauth2/token with the following perimeters
{
"code": "Security Code Returned from Step 1",
"client_id": "Client Id that was given to you in GApi Console",
"client_secret": "Client Secret that was given to you in the GApi Console",
"redirect_uri": "Redirect Uri you specified in the GApi Console",
"grant_type": "authorization_code"
}
However when I make this request with all the correct parameters I get this error
{
"error" : "invalid_request",
"error_description" : "Required parameter is missing: grant_type"
}
From the Google Plus Sign in Api
To make HTTP requests in The Play Framework you use the WS Library. I make the request like this
public static F.Promise<Result> OAuthCallback(String state, String code){
/*
Note:
- The GoogleStrategy class is just a class that holds all my GApi credentials
- The parameters (String state, String code) are just GET params from Step 1, returned by the GApi
*/
//Make URL builder
WSRequestHolder requestHolder = WS.url(GoogleStrategy.getTokenUrl);
//Set headers
requestHolder.setHeader("code", code);
requestHolder.setHeader("client_id", GoogleStrategy.clientId);
requestHolder.setHeader("client_secret", GoogleStrategy.clientSecret);
requestHolder.setHeader("redirect_uri", GoogleStrategy.redirectUri);
requestHolder.setHeader("grant_type", GoogleStrategy.grantType);//GoogleStrategy.grantType = "authorization_code"
//Make HTTP request and tell program what to do once the HTTP request is finished
F.Promise<Result> getTokenPromise = requestHolder.post("").map(
new F.Function<WSResponse, Result>() {
public Result apply(WSResponse response){
return ok(response.asJson());//Returning result for debugging
}
}
);
return getTokenPromise;//Return promise, Play Framework will handle the Asynchronous stuff
}
As you can see, I set the header grant_type. Just to make sure setting headers was working I made a program that spits out the headers of a request in NodeJS(Source) and this was the result
{
"HEADERS": {
"host": "127.0.0.1:3000",
"code": "4/qazYoReIJZAYO9izlTjjJA.gihwUJ6zgoERgtL038sCVnsvSfAJkgI",
"grant_type": "authorization_code",
"client_secret": "XXXX-CENSORED FOR SECURITY PURPOSES-XXX",
"redirect_uri": "http://127.0.0.1:9000/api/users/auth/google/callback",
"client_id": "XXXX-CENSORED FOR SECURITY PURPOSES-XXX",
"content-type": "text/plain; charset=utf-8",
"connection": "keep-alive",
"accept": "*/*",
"user-agent": "NING/1.0",
"content-length": "14"
}
}
I think those are not to be sent as headers but as a body. In the link you provided there is an example:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=8819981768.apps.googleusercontent.com&
client_secret={client_secret}&
redirect_uri=https://oauth2-login-demo.appspot.com/code&
grant_type=authorization_code
So pass them to your post call:
StringBuilder sb = new StringBuilder();
sb.append("code=").append(code)
.append("&client_id=").append(GoogleStrategy.clientId)
.append("&client_secret=").append( GoogleStrategy.clientSecret)
.append("&redirect_uri=").append(GoogleStrategy.redirectUri)
.append("&grant_type=").append(GoogleStrategy.grantType)
requestHolder.setContentType("application/x-www-form-urlencoded")
.post(sb.toString());
How can i call Auth Authentication using Restfull
i want to send :
Authorization: OAuth realm="Photos",
oauth_consumer_key="dpf43f3p2l4k3l03",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="137131200",
oauth_nonce="wIjqoS",
oauth_callback="http%3A%2F%2Fprinter.example.com%2Fready",
oauth_signature="74KNZJeDHnMBp0EMJ9ZHt%2FXKycU%3D"
I dont khonw more about Auth. so please help.
Since you are using HTTP client, it becomes very easy to send this header as a part of request. This can be accomplished as follows:
HttpGet request = new HttpGet("http://yoursite");
String authStr = "";// Your string starting from OAuth realm="Photos",oauth_consumer_key="dpf43f3p2l4k3l03" ....
request.setHeader("Authorization", authStr );
Once you execute this request, a Authorization header is sent to the server.
I'm using rest assured to test API's.am facing issues in making a request with below configuartion using rest assured.
Request type : POST
Headers:
Content-Type :text/plain
api-key : 12263783493
user : emailid
Cookie : changesetId=4604
Body type-: raw : Text
applyToAllMapsOnController=false&applyToAllMaps=false (this is the text in the request body to be passed)
Below is what i tried but I'm getting 400 bad request
Response response= (Response) RestAssured.given().
header("Content-Type", "text/plain").
header("charset","utf-8").
header("api-key","dV43+Rbr9uncPd&;ydiQx]uUFX2").
header("user","P2899445,Bhavan Ramakrishnappa").
cookie("cookie", "changesetId="+Number).
body("applyToAllMapsOnController=false&applyToAllMaps=false").
when().
post(servicelevel);
can someone help me how to pass cookie in header and raw text in the body.
You can do multiple things to Debug the issue.
Try passing ("cookie", "changesetId="+Number) as a header
use when().log().all so that you can see what is the Request being Sent.