Can some one help me with working code for Restassured post request with Authorization Header - oauth-2.0

I'm new to Restassured Webservice automation.
I'm able to get OAuth2 token and save it to a string. But when I pass this string in Authorization header, I'm getting 403 error.
Working code to store token in a string:
`String response = given()
.params("grant_type", "XXX", "scope", "XXX")
.auth()
.preemptive()
.basic("XXX","XXX")
.when()
.post("api/path")
.asString();
JsonPath jsonPath = new JsonPath(response);
accessToken = jsonPath.getString("access_token");
String pswd = "Bearer " + accessToken; `
Code not working is below:
`given().header("Authorization", pswd)
.body(content).with().contentType("application/json")
.when()
.post("/api/path")
.then().statusCode(200);`
I'm getting 403 error.

Can you try the following
`given().auth().oauth2(accessToken).
.body(content).with().contentType("application/json")
.when()
.post("/api/path")
.then().statusCode(200)`

Related

Rest Assured basic auth issue

I have an endpoint which works perfectly fine when I use Postman with Basic Auth. However, when I tried it in Rest Assured it returns 401. I have tried both different auth methods in rest assured and none of them worked for me so far. Need help!
RequestSpecification requestSpec;
String baseURI = "http://qa3-phoenix.labcorp.com";
String basePath = "/phx-rest/healthcheck/ping";
RestAssured.useRelaxedHTTPSValidation();
RestAssured.baseURI = baseURI;
requestSpec = new RequestSpecBuilder()
.setContentType(ContentType.JSON)
.build();
Response response = RestAssured
.given()
.spec(requestSpec)
.auth().basic("username","password")
.when()
.get(basePath)
.then()
.extract().response();
One can use directly the Authorization header with base64 encoded username and password and omit the auth() part.
Code example:
String authBasic = Base64.encode(String.format("%s:%s", username, password));
rest()
.header("Authorization", String.format("Basic %s", authBasic))
useRelaxedHTTPSValidation() is a workaround when the server is not using a valid certificate or you bump into SSLPeerUnverifiedException. In most of the scenarios this does not happen.
So try removing useRelaxedHTTPSValidation().
Can you also try the below approach:
While creating your RequestSpecification, can you add an object of authentication scheme to your RequestSpecification and then use that to create http requests.
RequestSpecBuilder req = new RequestSpecBuilder();
PreemptiveBasicAuthScheme auth = new PreemptiveBasicAuthScheme();
auth.setUserName("");
auth.setPassword("");
req.setAuth(auth);
req.build();
May be you can think of creating your RequestSpec from a separate class or package for better re-use.
Let me know if this helps, or the stacktrace.

Unable to get the LTPA token using Rest assured

I am new to rest assured, I want to perform some get and post for test data generation using rest assured. But I am unable to get the LTPA token and pass them to post. This works with postman but I want to do it through java. Any help
final String uri = "https://XXXX/Rest/XXXXX?user=XXXXX&pass=XXXX";
final Response response = RestAssured.given().relaxedHTTPSValidation().accept(ContentType.JSON).get(uri);
System.out.println(response.prettyPrint());
Map<String, String> allCookies = response.cookies();
System.out.println(allCookies);
Output
{JSESSIONID=XXXXXXX:-1}
but i do not see the LTPA2 token
Your LTPA2 token must be in Response headers.
You can get the response headers by
response.headers ();
In case if LTPA token is also not available in headers then share the screenshot of postman so I can help you out.

Sending OAuth token works in Postman but does not work in RestSharp

I tried to send a bearer token to an Auth0 API using Postman and it works perfectly.
I then tried the same using RestSharp (in c#) but it doesn't work at all.
Below is my code. I've tried many different formats but none of them work.. Is there any other way I can try to make it work?
var client = new RestClient("http://domain.auth0.com/api/v2/users");
RestRequest request = new RestRequest(Method.GET);
//request.AddHeader("authorization", "Bearer eyJhbGcJ9.eyJhdWQiOiJ6VU4hVWUE2.token");
//request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
//request.AddHeader("Accept", "application/json");
//RestClient client = new RestClient("http://domain.auth0.com");
//RestRequest request = new RestRequest("api/v2/users", Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Accept", "application/json");
request.AddParameter("Authorization",
string.Format("Bearer " + "eyJhbGciOI1NiIsI9.eyJhdWQiOiWmVhTWpD2VycyI6eyJhY.token"),
ParameterType.HttpHeader);
//request.AddParameter("Authorization",
// String.Format("Bearer {0}", token),
//ParameterType.HttpHeader);
var response = client.Execute(request);
PS: the token was changed.
The problem is that you're using an HTTP URL. When you issue the first request the token is included, but you receive a redirect response informing that you should be calling the HTTPS endpoint.
Since RestSharp will not include the token in the second request performed automatically due to the first redirect response you get an unauthorized response.
You need to update the URL to be HTTPS which will prevent the redirect and as a consequence solve your problem. If you want to make multiple authenticated request using the same client you also change your code to be:
using RestSharp;
using RestSharp.Authenticators;
class Program
{
static void Main(string[] args)
{
// Use the HTTPS scheme
var client = new RestClient("https://[domain].auth0.com/api/v2/users");
client.Authenticator = new OAuth2AuthorizationRequestHeaderAuthenticator(
"eyJhbGciJIUz.eyJhdWQi4QW5OXhCNTNlNDdjIn0.vnzGPiWA", // Update the token
"Bearer");
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine("{0}", response.StatusCode);
}
}
If you really need to handle redirects and still send the token, check: https://github.com/restsharp/RestSharp/issues/414

WSO2 Oauth2 Authentication - Provided Authorization Grant is invalid

I'm testing the WSO2 Identity server using the Oauth 2.0 with a Python login application. The routine which I adjusted from another IdP server, throws an error at the token authorization step, after successfully passing through step 1 which is obtaining the request code. The error returning from the WSO2 server is:
"Provided Authorization Grant is invalid"
Console Log
*** start of login ***
Code received = 23618215e0ee701b973f548a3f8e7dda
Token Request Answered = <Response [400]>
Token Request Text = {"error":"invalid_grant","error_description":"Provided Authorization Grant is invalid."}
Token Request URL = https://extbasicpacman05.podc.sl.edst.red.com:9443/oauth2/token
Token Request Encoding = None
Code:
#print "Send Token Request now"
# prepare lookup of token using code as input
verify='/home/claudef/tmp/oauth_2/oauth/wso2.pem'
url = "https://extbasicpacman05.podc.sl.edst.red.com:9443/oauth2/token"
payload = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'code': str(code), 'redirect_uri': 'http://localhost/resources/oauth2Callback' }
urllib.urlencode(payload)
headers = { 'application' : 'x-www-form-urlencoded' }
r = requests.post(url, data=payload, headers=headers, verify=verify)
print "Token Request Answered = " + str(r)
print "Token Request Text = " + str(r.text)
print "Token Request URL = " + str(r.url)
print "Token Request Encoding = " + str(r.encoding)
Any hint how to fix the authorization grant using a code value is welcome.
Just identified the error cause, indeed its a coding error, as the callback URL contained a missing port definition. I've corrected the statements to the new setting and the token returned successfully from the WSO2 server. The problem is solved.
The error message "invalid grant" is somehow confusing, maybe a suggestion
for future improvements.
verify='/home/claudef/tmp/oauth2/oauth/wso2.pem'
url = "https://extbasicpacman05.podc.sl.edst.red.com:9443/oauth2/token"
payload = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'authorization_code', 'code': str(code), 'redirect_uri': 'http://localhost:8080/resources/oauth2Callback'}
urllib.urlencode(payload)
headers = { 'application' : 'x-www-form-urlencoded' }
r = requests.post(url, data=payload, headers=headers, verify=verify)

How can I use the grant_type=password oauth flow with salesforce.com?

I'm trying to get an authorization token using the Username-Password flow (as described in the final section of this article).
I'm sending the following request (using Python's httplib, in case that's relevant):
https://login.salesforce.com/services/oauth2/token
POST data:
username=<un>&client_secret=<consumer_secret>&password=<pw+token>&grant_type=password&client_id=<consumer_key>
And getting the response:
400 Bad Request
{"error":"unsupported_grant_type","error_description":"grant type not supported"}
Is the password grant_type really unsupported, or am I missing something? It seems to give this error even when I'm sending a grant_type that definitely does work (such as authorization_code).
Note that I've tried the suggestions in the answer here, and they don't work for me.
Typically this is because the content-type header has not been set to the correct value, it should be application/x-www-form-urlencoded.
Also make sure your parameters are correctly encoded (especially if you're building the POST payload by hand).
Below is detailed function/logic on how to use grant_type=password oauth flow with salesforce.com in JAVA:
// Authenticate via OAuth
JSONObject response = oauthLogin();
System.out.println("Login response: " + response.toString(2));
if (!response.has("access_token")) {
throw new Exception("OAuth failed: " + response.toString());
}
..........................
private static JSONObject oauthLogin() throws Exception {
org.eclipse.jetty.client.HttpClient jettyHttpClient = new org.eclipse.jetty.client.HttpClient();
jettyHttpClient.start();
String url = LOGIN_SERVER + "/services/oauth2/token";
ContentExchange exchange = new ContentExchange();
exchange.setMethod("POST");
exchange.setURL(url);
String message = "grant_type=password&client_id=" + CLIENT_ID
+ "&client_secret=" + CLIENT_SECRET + "&username=" + USERNAME
+ "&password=" + PASSWORD;
exchange.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
exchange.setRequestContentSource(new ByteArrayInputStream(message
.getBytes("UTF-8")));
jettyHttpClient.send(exchange);
exchange.waitForDone();
return new JSONObject(new JSONTokener(exchange.getResponseContent()));
}
You must set the grant_type as "password" in the form data. See below.
The form data should be passed ad
grant_type=password&username=nilavghosh%40gmail.com&password=******

Resources