Flutter post request headers do not appear on Google Cloud Function - flutter

I am doing a post request in flutter to a google cloud function:
final uri = Uri.parse(
'https://example.cloudfunctions.net/send_to_queue');
final bearer = 'Bearer ${await user.getIdToken()}';
final response = await http.post(uri, body: json.encode(data),
headers: {HttpHeaders.authorizationHeader: bearer, 'Content-Type': 'application/json'});
In the Google Cloud I print(request.headers) I see a bunch of headers but no Authorization or Content-Type headers.
What should I do?
P.S. Same issue in here Flutter calling firebase cloud function admin.auth.updateUser but I don't want to use a callable function

The browser was sending an OPTIONS request (preflight) before the POST.
I needed to change the Google Cloud Function to handle this:
def main(request):
# Set CORS headers for the preflight request
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
# Get token from request
token = request.headers.get('Authorization').split('Bearer ')[1]
etc..

Related

Set authorization token dynamically to axios per request in nestjs

is it possible to set the authorization token dynamically to Axios per each request?. axios is used for requests forwarded from service.
You can add it to the headers via the options parameter
const res = await axios.get('https://httpbin.org/get', {
headers: {
'Authorization': 'Bearer ey…'
}
});

Request blocked by CORS policy: Header field is not allowed by Access-Control-Allow-Headers

I am using Axios to make a POST request with the following headers:
let reqConf = {
headers: {
'x-xsrf-token': '....',
'Content-Type': 'Application/json',
'Access-Control-Request-Headers': 'content-type',
'Access-Control-Allow-Headers': 'Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Allow-Headers, x-xsrf-token'
}
}
I make a post call like so: const response = await axios.post(url, request, reqConf )' I get the following error message: Request blocked by CORS policy: Request Header x-xsrf-token field is not allowed by Access-Control-Allow-Headers`, but if I remove that header from my request I still get the same error but for other headers such as Content-Type.
I have modified the server config to allow Header set Access-Control-Allow-Origin "*". I have set Access-Control-Allow-Headers with all of my headers and my OPTIONS call returns 200 in browser. Is there something else I am missing in my request?

Works via Postman but not in Flutter: API call with GCS pre-signed URL

I'm trying to upload a video file to GCS using a pre-signed url. I've managed to create the url via Google but now I am facing a problem using it.
Upload works in Postman, got response 200.
postman body, postman params
Code copied from Postman results in 403 Forbidden (SignatureDoesNotMatch):
Future<http.StreamedResponse> uploadVideo(
{required String uploadURL, required String filePath}) async {
var headers = {'Content-Type': 'application/octet-stream'};
var request = http.MultipartRequest('PUT', Uri.parse(uploadURL));
request.files.add(await http.MultipartFile.fromPath('file', filePath));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
return response;
}
This is the error I am getting from Google:
<?xml version='1.0' encoding='UTF-8'?><Error><Code>SignatureDoesNotMatch</Code><Message>The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.</Message><StringToSign>GOOG4-RSA-SHA256
20210803T082850Z
20210803/auto/storage/goog4_request
6d513846a3db49f949b0d2eea8f04b90f918b3b94588c3ed55ed3620b7d7e1f6</StringToSign><CanonicalRequest>PUT
/phonedo-interviews/app-test/007/2.mp4
X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=interviews%40interviews-317011.iam.gserviceaccount.com%2F20210803%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20210803T082850Z&X-Goog-Expires=900&X-Goog-SignedHeaders=content-type%3Bhost
content-type:multipart/form-data; boundary=dart-http-boundary-6w1yq6BQN3EkGBrhHZnwidOXZsBecsgSwTT3nBjB9vQCToHt0cg
host:storage.googleapis.com
content-type;host
UNSIGNED-PAYLOAD</CanonicalRequest></Error>
Note: I needed Content-Type to be application/octet-stream so I disabled that header in Postman's automatic headers and added Content-Type manually. When I didn't do that I also got 403.
The solution was to send the file in binary.
Here is the working code:
Future<http.Response> uploadVideo(
{required String uploadURL, required String filePath}) async {
var response = await http.put(
Uri.parse(uploadURL),
headers: {'content-type': 'application/octet-stream'},
body: File(filePath).readAsBytesSync(),
);
In your Postman headers, a Token is given to GCS (first line). Given that you need authorization, Postman probably has this Token saved somewhere application-wise.
In this flutter code, the headers you're giving do not include an Auth token and therefore you're receiving a 403 error.

How to send a token in a request in flutter?

I am making a flutter application, and i have written a server in django. When i send a token to my server for authentication then my server sends me an error of undefined token. Without token all requests works fine, but when i add a token then it gives me an error
{detail: Authentication credentials were not provided.}
But When i add token in modheader, my server works fine
Authorization: Token bff0e7675d6d80bd692f1be811da63e4182e4a5f
This is my flutter code
const url = 'MY_API_URL';
var authorization = 'Token bff0e7675d6d80bd692f1be811da63e4182e4a5f';
final response = await http.get(
url,
headers: {
'Content-Type': 'application/json',
'Authorization': authorization,
}
);
final responseData = json.decode(response.body);
print('responseData');
print(responseData);
try this:
Map<String, String> headers = {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Token bff0e7675d6d80bd692f1be811da63e4182e4a5f'
};
& use them in request
final response = await http.get(
url,
headers: headers,
);
As I don't know to work on your API so I can't tell you the exact answer.
Check that, Is your backend taking authorization by header or body or
I'll suggest you first make authorization by tools like postman then
if that succeeds then try to implement that in your app.

Node Js Restapi - Calling Post Method in Flutter Doesn't Work

I have local api and jwt by node js i want to send my username and password from flutter and send it to node js to give me this token and later i will save it in local storage but when i tell flutter post to the api doesn't post
my code :
You can use http method here like below Future example
Future postContact(access_token,name,email,phone,message) async {
String apiUrl = '$_apiUrl/user/contact-us';
http.Response response = await http.post(apiUrl,headers: {
"Accept": "application/json",
"Accesstoken": "Bearer $access_token"
}, body: {'name':'$name','email':'$email','phone':'$phone','message':'$message'});
print("Result: ${response.body}");
return json.decode(response.body);
}