what is the correct way to pass Bearer token in header section of my HTTP.Post in flutter - flutter

My Post API need a customer_id in body but also need a bearer token. I am passing it using following code
var myId="1005",
var token="my Token here"
var response = await http.post(Uri.parse("http://haulers.tech/jashn/mobile/home/shoutouttype"),
body: ({
"customer_id":myId.toString,
}),
headers: ({
"Authorisation": token.toString, //here I want to pass Bearer Token
})
);
This code return status code 401.

Pay attention to the word Bearer its must be Capitalized other ways it wont work, not sure whats the reason, but for flutter http calls make sure to capitalize that word like this
var response = await httpClient.post(
url,
headers:{
"Accept": "application/json",
"Content-type": "application/json",
"Authorization": "Bearer $token"
},
body :{some body});

Bearer tokens are usually sent preceded with Bearer : the following key value pair:-
"Authorization": "Bearer {TOKEN}"
Should work.

Related

Autorization using bearer token failing

Friends
I am accessing an API using bearer token authorization and getting HTTP status 401.
The problematic code is Dart code (in a Flutter app). I have Swift code that accesses the same API so I can check the headers I am passing.
The Dart code:
var client = http.Client();
var url = Uri.https(<site>, <path>);
Map<String, String> body = {
<Hash entries to define request>
};
var headers = <String, String>{
"Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8",
"Accept" : "application/json, text/javascript, */*; q=0.01",
"Authorization" : "Bearer <Hex token>",
};
var response = await client.post(url, headers: headers, body: body);
http is from: import 'package:http/http.dart' as http;
The hex token is taken from a successful login. It is the same as I see after a successful login with the Swift app.
The "Accept" and "Content-Type" are also the same as the Swift app.
In result the statusCode is 401 and reasonPhrase is "Unauthorized"
The Swift app is working perfectly
This was not the problem I thought.
The Authorization header is ignored by the server and it does some cookie magic to authorise.
In Swift the cookies were set without my intervention. So I never understood that the Bearer.... authorization was ignored.

How to add API key to Axios post request for mailchimp

I'm trying to set up an axios post request to add members to an audience list, but I can't figure out how to add the API key (keeps giving error 401: 'Your request did not include an API key.'). I've tried a bunch of things in the "Authorization" header, like what I put below (also: "Bearer ${mailchimpKey}", "${mailchimpKey}", "Bearer ${mailchimpKey}", "Basic ${mailchimpKey}", and probably more...).
I also don't know what the "username" would be, but "any" worked when I tested the API elsewhere.
Does anyone know how I should set this up?
axios
.post(
`https://${server}.api.mailchimp.com/3.0/lists/${list_id}/members`,
{
email_address: email,
status: "subscribed",
},
{
"User-Agent": "Request-Promise",
Connection: "keep-alive",
Authorization: `Basic any:${mailchimpKey}`,
// Testing on localhost
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type",
}
)
If your intention is to use HTTP Basic authentication, just use the Axios auth config option
axios.post(
`https://${server}.api.mailchimp.com/3.0/lists/${encodeURIComponent(list_id)}/members`,
{
email_address: email,
status: "subscribed",
},
{
auth: {
username: "anystring",
password: mailchimpKey
},
headers: { // personally, I wouldn't add any extra headers
"User-agent": "Request-Promise"
}
}
)
HTTP Basic auth headers look like
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
where the string after "Basic" is the Base64 encoded "username:password" string. Axios provides the auth option as a convenience so you don't need to encode the string yourself.
Some other problems you had were:
Adding request headers outside the headers config option
Attempting to send Access-Control-Allow-Origin and Access-Control-Allow-Headers as request headers. These are response headers only. Adding them to your request will most likely cause more CORS errors

Sending int and boolean at body of http post method in flutter

Hi I have a http post as
final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": false,
"servisID": 1
}
);
But when I try this post method I get "Unhandled Exception: type 'bool' is not a subtype of type 'String' in type cast". I can change the API to expect string but I wonder if there is a work around to send int or boolean.
Note that When I send a similar request on postman everything is fine.
Edit:
Postman:
POST /someendpoint/ HTTP/1.1
Host: somehost
Authorization: Token sometoken
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 20582fd0-c980-2d0d-fb2f-3bdd87d767f5 \
{
"isItTake": false,
"servisID": 1
}
Try sending the request body values as Strings and see if that works. I've faced this issue before with type mismatch with the request bodies of http requests and I'm not quite sure as to why it throws exceptions like that even though the documentation for the api clearly specifies the type for each value in the request body. Try this:
final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": 'false',
"servisID": '1'
}
);
Or in case if you have your values in some bool and int variables:
final http.Response response = await client.post(
'http://someurl/',
headers: {
HttpHeaders.contentTypeHeader: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": token
},
body: {
"isItTake": isItTake.toString(),
"servisID": servisID.toString()
}
);
Use String encoded = json.encode(theMap); then post encoded. If you need a particular character encoding (e.g. utf-8) then further encode the string using utf8.encode(encoded) and post the resulting byte array. (The second step should be unnecessary for utf-8 as I think that is the default.)
It's worth considering what the 3 variants do:
List<int> - sends an opaque byte array
String encodes the string into bytes using a character encoding - and sends the byte array
Map<String, String> - encodes the string key/value pairs in
x-www-form-urlencoded and sends that.
If you want to send more complex data then you need to convert it into one of the above (and the server needs to know how to decode it). That's where the content-type header is useful. Ultimately, the server receives a byte array and converts it back into, for example, a string, or some json, or a set of form fields, or an image. It knows how to do this based on the header and any specified encoding.
Complete Credit: Source

401 Auth error with apps script connecting to 3rd party API

I am beating my head up trying to get this to work.
Any assistance would be appreciated.
I have tested the auth in Insomnia and Postman and its working fine but not with apps script. I am getting a "401 Authorization Required" response.
function myFunction() {
var url = "https://api.tempo.io/core/3/worklogs/project/MYPROJECT";
var token = "THISISATOKEN";
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": "Bearer "+ token,
"muteHttpExceptions": true
};
var options = {
"method" : "get",
"headers" : headers
};
var response = UrlFetchApp.fetch(url,headers);
Logger.log(response);

Paypal UNSUPPORTED_MEDIA_TYPE

I am trying to get an access token from paypal's authorization api.
When I make post request to the api I get UNSUPPORTED_MEDIA_TYPE i.e. 415 response.
Below is the snippet that I used.
const auth = await fetch(PAYPAL_OAUTH_API, {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${ basicAuth }`
},
body: JSON.stringify({"grant_type": "client_credentials"})
});
I have fixed my issue by setting Content-Type to application/x-www-form-urlencoded.
My guess is paypal accepts only application/x-www-form-urlencoded for authorization api.
I ran into same issue, and the solution is following (using Postman):
Select POST
Add Token into Authorization, type is Bearer-Token
Select Content-Type: application/json in headers
Use RAW as body, and in TEXT dropdown, select JSON (application/JSON)
Copy body as raw object and change info accordingly.
Step 4 and 5 are what solved the error, you must send raw json object.