Rest Assured - Error 404 when authenticating using localhost - rest-assured

I'm testing an API using localhost, in the manual tests it went well using Postman, as follows in the screenshot:
Postman
As the screenshot shows, it's necessary to send the username and password in the request body, then the API returns the Authentication key in the response header, and the Status 200 OK.
But when I tried to automate the test to see if I could retrieve the key from the header response, the test failed with statusCode 404, and I can't even proceed to see if it gets the authorization in the header. Is there something I'm missing when automating this kind of request?
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import static io.restassured.RestAssured.given;
public class reusableMethods {
public static String getSessionKey() {
RestAssured.baseURI = "http://localhost:3000";
Response res =
given().log().all().
header("Content-Type", "application/json").
body("{\n" +
" \"email\": \"admin#test.com.br\",\n" +
" \"password\": \"passw0rd\"\n" +
"}").
when().
post("/api/cms/v1/auth/login").
then().assertThat().
statusCode(200).
extract().response();
String headerValue = res.header("Authorization");
System.out.println(headerValue);
return headerValue;
}
When I run the test, I always get the same error, as follows along with the log:
Request method: POST
Request URI: http://localhost:3000/api/cms/v1/auth
Proxy: <none>
Request params: <none>
Query params: <none>
Form params: <none>
Path params: <none>
Headers: Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies: <none>
Multiparts: <none>
Body:
{
"email": "admin#test.com.br",
"password": "passw0rd"
}
java.lang.AssertionError: 1 expectation failed.
Expected status code <200> but was <404>.

You can use auth() method to pass Authentication.
It has multiple options, you need to see which one suits your authenication.
If your are using OAuth token, then it will be like:
Response res = given()
.auth().oauth2("Your token")
.log().all().
header("Content-Type", "application/json").
body("{\n" + " \"email\": \"admin#test.com.br\",\n" +" \"password\": \"passw0rd\"\n" +"}").
when().
post("/api/cms/v1/auth/login").
then().
assertThat().
statusCode(200).extract().response();

Related

How to send request to another server in shelf dart

I need to make a request to my firebase rtdb from my shelf server hosted on 127.0.0.1, I have the url and the db secrets. But whenever i try to make a get request to the db url using the http package, i get a 401 error.
My code:
import 'dart:io';
import 'package:http/http.dart';
import 'package:firebase/firebase_io.dart';
class FirebaseLocalClient {
void putSudokuBoard() async {
var a = await get(
Uri.parse(
"<db url>"),
headers: {
"Authorization": "Bearer <your database secret>",
'Content-Type': "application/js"
});
print(a.statusCode);
//print(a.runtimeType);
}
}
void main(List<String> args) {
FirebaseLocalClient().putSudokuBoard();
}
I call this code from a shelf server(similar to the code in main function), but running it here itself recieves a 401 error.
I am not able to understand why i am recieving a 401 error, i have the db secrets and yet i am unable to get the data at that location. I tried using the admin sdk json but recieved 401 on that too
The output when i use a.body:
The output when i use a.statuscode:
If you are using the db secrets, it looks like you need to append the auth param.
per https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-uri-params
curl 'https://docs-examples.firebaseio.com/auth-example.json?auth=CREDENTIAL'
Remove the Authorization header and try it in curl

AADSTS90014: The request body must contain the following parameter: 'grant_type'

I am trying to send a post request to receive my access token from https://login.microsoftonline.com/common/oauth2/v2.0/token. When I tried this in my REST client, it works, but when I try to integrate it to my app, it sends me a error 400 Bad Gateway, with the message AADSTS90014: The request body must contain the following parameter: 'grant_type'. I tried searching for answers, and found out that I need to implement headers in my post request, so I did that, but it still won't work. Any ideas?
Http Imports:
import { HttpClient, HttpHeaders, HttpRequest } from '#angular/common/http';
Call to post request:
var url=this.outlook_authentification_endpoint+"token";
var query_parameters=JSON.stringify({grant_type:"authorization_code", client_id:this.outlook_client_id, code: this.outlook_user_code, client_secret: this.outlook_secret_key, redirect_uri: this.outlook_redirect_uri});
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded'
})
};
this.query_service.postOutlook(url, query_parameters, httpOptions, (data)=>
{
console.log(data);
});
Call to the post function:
public postOutlook(url, query, headers, callback)
{
this.operation_pending=true;
this.http_client.post(url,query, headers).subscribe((data)=>
{
this.operation_pending=false;
callback(data);
});
}
Can anyone see where my error is?
You are using wrong OAuth2 flow (the way of getting tokens). You are using the Auth code grant, which cannot be used in browser applications, because you would have to keep your client secret in JavaScript, which means make it public. So you cannot access the /token endpoint either.
You should use the Implicit grant, which is designed for browser applications. Then you get tokens right into your Angular application without the need of going to the /token endpoint.

Siesta iOS POST request errors out with "unsupported URL"

I am having trouble with Siesta - an iOS REST Client Framework https://bustoutsolutions.github.io/siesta/.
Below is a simple example of a POST request to a REST API server, which fails with a "unsupported URL" error. Does anybody out there have any experience with Siesta and what could be wrong?
Siesta configuration & login server call
let api = Service(base: "http://myapidomain.net/rest")
enabledLogCategories = LogCategory.all
let parameters = ["username": "username", "password": "password"]
api.resource(url: "users/login").request(.POST, json: NSDictionary(dictionary: parameters)).success { data in
debugPrint("success logging in")
}.failure { error in
debugPrint("failed to log in")
}
Debug log
[Siesta:Configuration] Computing configuration for Siesta.Resource(users/login)[]
[Siesta:Configuration] Applying config 0 [Siesta default response transformers] to Siesta.Resource(users/login)[]
[Siesta:NetworkDetails] Request:
headers: (1)
Content-Type: application/json
[Siesta:Network] POST users/login
[Siesta:Network] – ← POST users/login
[Siesta:NetworkDetails] Raw response headers: –
[Siesta:NetworkDetails] Raw response body: 0 bytes
[Siesta:NetworkDetails] Response after transformer pipeline: (new data)
Failure
userMessage: "unsupported URL"
nsError: "unsupported URL"
"failed to log in"
The Service.resource(url:) method — the one with the parameter labeled url: — expects a complete URL. It looks like you want Service.resource(_:), which takes a path relative to the Service’s base URL.
Try:
api.resource("users/login")

Google Oauth 2.0 authentication for limited input device not working except on curl

I am trying to use a custom java application of mine to upload videos to my youtube account via an access limited device like a Raspberry pi running as a server.
For this I am using the Google Oauth 2.0 for limited input device as a reference.
I followed the steps mentioned with my custom java application, Fiddler and curl, the surprise is as follows:
All of the calls worked right as mentioned by Google Oauth 2.0 for limited input device for curl.
But issues were observed with Fiddler and my custom java app for the following call:
When I am trying to get the access token from Google server (Step 4 from Google Oauth link) by posting similar request:
POST /o/oauth2/token HTTP/1.1
Host: accounts.google.com
Content-Type: application/x-www-form-urlencoded
client_id=1084945748469-eg34imk572gdhu83gj5p0an9fut6urp5.apps.googleusercontent.com&
client_secret=hDBmMRhz7eJRsM9Z2q1oFBSem&
code=4/YMSlR3fSCC1NtUh073DuZKTJJ3ss&
grant_type=http://oauth.net/grant_type/device/1.0
but instead of getting the 'access_token' as response I am getting the following :
Status Code:400 Response: { "error" : "invalid_request",
"error_description" : "Required parameter is missing: grant_type" }
Note : With or without url encoding, my problem stays the same.
I am unable to understand what the issue is with my custom java app or with fiddler, Please help.
Following are my fiddler requests:
(One can get oauth credentials (client_id and client_secret) by following this)
Fiddler request:
(url encoded, obscured client secret)
POST HTTP/1.1
https://accounts.google.com/o/oauth2/token?client_id=308065994473-ur9dd7003ajs6mvr5s4kqnugr6j8tsf2.apps.googleusercontent.com&client_secret=XXXXXXXXXXXXXXX&code=4%2FWR-qiTquqB0e4-0LCy0-7rZ2kkE2&grant_type=http%3A%2F%2Foauth.net%2Fgrant_type%2Fdevice%2F1.0
Content-Type: application/x-www-form-urlencoded
(non url encoded, obscured client secret)
POST HTTP/1.1
https://accounts.google.com/o/oauth2/token?client_id=308065994473-ur9dd7003ajs6mvr5s4kqnugr6j8tsf2.apps.googleusercontent.com&client_secret=XXXXXXXXXXXXXX&code=4/WR-qiTquqB0e4-0LCy0-7rZ2kkE2&grant_type=http://oauth.net/grant_type/device/1.0
Java code project is available at (maven project, check the test case for the Oauth calls):
https://docs.google.com/file/d/0B8ltWBtPF-DVMDZFNHNMZXpCQlk
The parameters need to be added in the http post request body not in the url, Google documentation is confusing on this part.
public synchronized HttpResponse executePOST(HttpEntity httpEntity, String path) throws IOException {
if (!parameters.isEmpty()) {
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
}
httpPost = new HttpPost(path);
logger.info(target.toHostString());
logger.info(httpPost.getURI().toString());
logger.info(httpPost.getRequestLine().toString());
for (Header header : headers) {
logger.info(header.getName() + ": " + header.getValue());
httpPost.addHeader(header);
}
httpResponse = httpClient.execute(target, httpPost);
return httpResponse;
}

how to add content-type to Twilio response?

How to add content-type to Twilio Response? I am getting 502 bad gateway error and the error says that it could be because of missing Content-Type. But I do see that the response has the Content-type. So what could be going wrong? I am also seeing the twilio reason is connection-time out! What does that mean? This is related to my earlier post at: An attempt to retrieve content from returned the HTTP status code 502. Please check the URL and try again
Response - The HTTP headers and body of your server's response to Twilio
Headers
Content-Type text/html
Transfer-Encoding chunked
X-Twilio-Reason connection timed out
Body
1
<html><head><title>502 Bad Gateway</title></head><body><h1>Bad Gateway</h1>An upstream server returned an invalid response.</body></html>
Can somebody help me to find out why twilio is giving error while accessing my API?
This is what I have in my controller:
public class TestController : ApiController
{
[HttpPost]
public HttpResponseMessage Post([FromBody]SmsRequest smsReq)
{
string smsReqUpper = smsReq.Body.ToUpper();
string testString = "TEST";
var response = new Twilio.TwiML.TwilioResponse();
if (smsReqUpper == testString)
{
response.Sms("Test Successful");
return Request.CreateResponse(HttpStatusCode.OK, response.Element);
}
else
{
string strBody = "Invalid Text Command. Please text the word TEST " ;
response.Sms(strBody);
return Request.CreateResponse(HttpStatusCode.OK, response.Element);
//return new TwiMLResult(response);
}
}
The Content-Type text/html bit refers to the 502 bad gateway response, not the actual response coming from your server. Add the "text/xml" content type to your request (I don't recognize the framework you are using) and you should be good to go.
To debug your response you can use curl -vvv [URL] until the Content-Type: text/xml part is present.

Resources