flutter: send Authorization Token along http header - flutter

I am making a request in postman with the same URL that i use in my UI code and in the header passing accept and Authorization with bearer token. In postman it is working completely fine and giving desired response but in flutter in my code the token not send to server when i print my header using print(response.headers) it print {x-powered-by: Express, connection: keep-alive, keep-alive: timeout=5, date: Thu, 30 Sep 2021 16:47:57 GMT, content-length: 429, etag: W/"1ad-Nsvj6qTf+5iQsO/n7VuLkLMax/M", content-type: application/json; charset=utf-8} that means the Authorization part not send along the request header how can i send the authorization and token along to http post request ? please guide me it take my long hours but still not working.
here is my code:
var token='somethings';
response = await http.post(uri,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode(account[i]));

headers: {
HttpHeaders.authorizationHeader: 'Basic your_api_token_here',
},

Related

Axios doesn't initiate POST request

I am using webdriverIO version 7 and axios in order to try to make login via API instead of doing it using UI.
This is my code:
getAuthToken({ email, password }) {
// axios
// .post('https://my-app.com/login', {
// j_username: email,
// j_password: password,
// CSRFToken: 'some-token',
// })
// .then((response) => {
// console.log('XXX');
// console.log(response);
// });
const data = {
j_username: email,
j_password: password,
CSRFToken: 'some-token',
};
axios({
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url: 'https://my-app.com/login',
}).then((response) => {
console.log('XXX');
console.log(response);
});
}
I am trying to do it in both ways as above but I don't get ever response printed in the console.
I tried to do the request via Postman and it is working fine.
Also I am monitoring the traffic on the site via Fiddler Everywhere app and when this method gets executed, then nothing is shown in the Fiddler.
On the other hand when I do it via Postman, Fiddler catches it.
This is Raw Postman Request data:
POST https://my-app.com/j_spring_security_check HTTP/1.1
User-Agent: PostmanRuntime/7.28.0
Accept: */*
Cache-Control: no-cache
Postman-Token: 39311680-b11c-4a65-8ff7-2f03b97bf5eb
Host: my-app.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------619522728182415185770824
Cookie: anonymous-consents=%5B%5D; cookie-notification=NOT_ACCEPTED
Content-Length: 436
----------------------------619522728182415185770824
Content-Disposition: form-data; name="j_username"
email#test.com
----------------------------619522728182415185770824
Content-Disposition: form-data; name="j_password"
123456
----------------------------619522728182415185770824
Content-Disposition: form-data; name="CSRFToken"
some-token
----------------------------619522728182415185770824--
This is Raw Request when I do it through Chrome
POST https://my-app.com/j_spring_security_check HTTP/1.1
Host: my-app.com
Connection: keep-alive
Content-Length: 90
Cache-Control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
sec-ch-ua-mobile: ?0
Upgrade-Insecure-Requests: 1
Origin: https://my-app.com
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: https://my-app.com/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cookie: JSESSIONID=some_id; dtCookie=some_data; anonymous-consents=%5B%5D; cookie-notification=NOT_ACCEPTED
j_username=ecx%40test.com&j_password=123456&CSRFToken=some_token
What am I doing wrong? Why it doesn't never log the response while doing it through axios?
Thanks!
The function is written correctly.
Postman passes additional details also which you can to look into.
Lets consider the scenarios which may cause the API call to fail:
Your function might not be correct.
The API is not configured properly.
Issues in the network.
Tackling the first scenario:
Check whether the function getAuthtoken() is getting invoked or not.
There might be an issue of CORS which you need to fix.
As you are send a JSON data, the server side must also accept the JSON data, or specify it in request headers. like
const data = {"name":"Example"}
axios.post('https://linkToApI.com', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'some_auth_method_like_authToken',
specify other necessary headers
},
data
})
Getting to the second scenario:
Configuring the server is important.
make sure there is not any cors issue which is getting in the way.
make sure server is accepting the request data which you are sending.
make sure if the request fails it sends a error response.
Additional changes in the code for debugging purposes:
Whatever code you use please try to add a catch block as if the promise fails we can get the error message why is it failing. below is the example:
axios({
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url: 'https://my-app.com/login',
}).then((response) => {
console.log('XXX');
console.log(response);
}).catch(e=>{console.log(e)}); // this will provide you with info why is it failing

API Gate away Is Blocked even when CORS is enabled

I'm trying to make an api to upload images to cloudinary like this
fd.append('photos', file);
fd.append('upload_preset',
CLOUDINARY_UPLOAD_PRESET);
axios({
url: CLOUDINARY_API,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
"Access-Control-Allow-Origin": "*",
'Access-Control-Allow-Headers': 'Origin',
'Access-Control-Allow-Credentials': true
},
data: fd
}).then(function(res) {
console.log(res);
}).catch(function(err) {
console.error(err);
})
})
but i recieve this error from the browser
Access to XMLHttpRequest at 'https://api.cloudinary.com/v1_1/******/mh/upload' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.Blockquote
You will need to remove the three "Access-Control-Allow-*" headers from the request you are sending.
The headers Cloudinary allows for cross-origin requests don't include those headers which you are sending and therefore the browser throws this error.
Below are the headers that are allowed for cross-origin uploads (under Access-Control-Allow-Headers):
curl -sD - -X OPTIONS https://api.cloudinary.com/v1_1/demo/image/upload
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Cache-Control, Content-Disposition, Content-MD5, Content-Range, Content-Type, DPR, Viewport-Width, X-CSRF-Token, X-Prototype-Version, X-Requested-With, X-Unique-Upload-Id
Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS
Access-Control-Max-Age: 1728000
Cache-Control: no-cache
Content-Type: text/plain; charset=utf-8
Date: Sat, 19 Dec 2020 09:49:48 GMT
Server: cloudinary
Status: 200 OK
Vary: Accept-Encoding
X-Request-Id: d1af2a2f8a986d9ebbd1f14399dd409d
X-UA-Compatible: IE=Edge,chrome=1
X-XSS-Protection: 1; mode=block
Content-Length: 0
Connection: keep-alive
EDIT: In addition, Cloudinary API doesn't have a parameter called "photos". The file to upload is sent in the "file" parameter.
Therefore, you would need to replace fd.append('photos', file); with fd.append('file', file);.

Flutter Filemaker API _find request

Im trying to make a http-request to Filemaker with Flutter(package:http/http.dart)
I can get the token normally, but if i try the make an _find request to Filemaker it always get's rejected(400 Bad Request) without any message.
In Postman I can do the exact same request without issue!
var body = { "query":[{
"loginName": "==testUser#test.com"
}]};
Response response = await post(url,
headers: {
HttpHeaders.authorizationHeader: 'Bearer $token',
HttpHeaders.contentTypeHeader: 'application/json'},
body: json.encode(body));
Found it:
Dart http adds: content-type: application/json; charset=utf-8
And Filemaker rejects this..
But now is the question why does Filemaker API rejects such an API Call?
SOLVED.
I was able to access one user in a FileMaker layout using Dio.
Dio dio = Dio();
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "Bearer ${token}";
Response recordResponse;
recordResponse = await dio.post(
findUrl,
options: Options(followRedirects: false, validateStatus: (status)
{return status < 500;}),
data: { "query":
[{
"username": "=Jake",
"password": "=password"
}]
}
);

Ionic 2 http post request remove default headers

I am new to Ionic 2. I make a http post request to my Spring Rest-api. As header I need to set the 'content-type': 'application/json', but the Ionic 2 sets automatically the content-type to application/json; charset=UTF-8, which is causing my REST service to respond with 415 status.
Here is my code:
register(user: User){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(apiUrl + 'users', user, {headers:headers})
.then((response: Response) => {
console.log(response);
console.log(JSON.stringify(user, null , 2));
console.log(JSON.stringify(headers, null, 2));
});
}
Here is the error I get when making the post request:
[00:46:35] error opening ws message: {"category":"console","type":"log","data":["error:
",{"status":415,"url":"**MY_URL**","headers":{"x-android-received-millis":"1512686795738","x-frame-options":"DENY","pragma":"no-cache","content-type":"application/json;charset=UTF-8","x-content-type-options":"nosniff","date":"Thu,
07 Dec 2017 22:46:35 GMT","strict-transport-security":"max-age=31536000 ; includeSubDomains","via":"1.1
vegur","connection":"keep-alive","x-android-sent-millis":"1512686795652","cache-control":"no-cache,
no-store, max-age=0,
must-revalidate","transfer-encoding":"chunked","server":"Cowboy","x-android-response-source":"NETWORK
415","x-android-selected-protocol":"http/1.1","expires":"0","x-xss-protection":"1;
mode=block"},"error":"{\"timestamp\":1512686795600,\"status\":415,\"error\":\"Unsupported Media
Type\",\"exception\":\"org.springframework.web.HttpMediaTypeNotSupportedException\",\"message\":\"Content
type 'application/x-www-form-urlencoded;charset=UTF-8' not supported\",\"path\":\"/api/users\"}"}]}
Check please in the error logs, the headers object. How can I leave only 'content-type': 'application/json'?
Thank you very much!

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.
headers: {
"Content-Type": 'application/json; charset=UTF-8',
"Accept": 'application/json; charset=UTF-8'
},
As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?
I managed to get it to work with the following headers
var headers = {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS, PUT",
"Content-Type": "application/json",
"Accept": "application/json"
};