How to send JWT token in flutter in a request header? - flutter

I'm trying to send a request to a server that requires a parameter called 'fid' sent in the header for autherization.
Here's what you can help me with.
Payload to be sent in the header 👇
{ "fid" : "Some alphaNum value", "type": "some type string" }
I would like to know how to use jwt encoding in flutter and how to use that in the header of a request to encode and send this payload across to the server for autherization. I'm planning to use HS256 algo for encoding. Since I'm new to the concept of Jwt, there might be errors in the way I asked this question. Please share your thoughts. I would also like to know how to use the secret key too -- like how to generate the key, and where in the request to send this.
Request 👇
fetchData({required String type, required String fid, String url}) async{
<How to get the json web token>
http.get(url, header : <What do I send here>);
}

you can use http or Dio package for calling API requests in flutter,
you can set headers as follows,
https://pub.dev/packages/dio
https://pub.dev/packages/http
final response = http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});

Related

Uploading file to S3 in Flutter Web (with link from backend)

I'm trying to upload a file to S3 picked with the filepicker package in flutter web. The backend provides me the link to upload the file, so in theory all I need to do is a PUT request to said link. The problem I'm having is (I think) properly sending the file in the body of the request, because if I upload the file directly to S3 with postman on the provided link, it works.
The code below is what I've been working on, after several iterations. I've tried forming the file with http.MultipartFile.fromBytes but the result is the same. I've also tried to send the request with a normal http.put request, and the error there is when I put a Multipart File in the body, if I try to json.encode, I get an error that it wasn't successful, if I don't encode it, it also gives a type error.
This current code is giving and XMLHttpRequest error, which from what I understand is probably due to a CORS error, the thing is I don't understand how that could be. Any input is appreciated!
Here is the code for uploading the image to the link provided by the backend:
Map<String, String> customHeaders2 = {
"x-amz-server-side-encryption-customer-key":
"",
"x-amz-server-side-encryption-customer-algorithm": "AES256",
"x-amz-server-side-encryption-customer-key-MD5":
"",
"Content-Type": "image/png",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "*/*",
};
final request = http.MultipartRequest(
'PUT',
//body of the response from request to the backend for the link
Uri.parse(jsonDecode(response.body)["data"]["data"]),
);
request.headers.addAll(customHeaders2);
request.files.add(
http.MultipartFile(
'file',
http.ByteStream.fromBytes(file.bytes!),
file.bytes!.length,
filename: file.name,
//contentType: MediaType('application', 'octet-stream'),
),
);
await request.send().then((value) => print(value.statusCode));
Thanks!

How to extract header values from http response?

I am using http post to send some information and get back the response.
final response = await http.post(
Uri.parse(
"some url"
),
headers: <String, String>{
'email': email,
'callbacktoken': callbacktoken
},
);
When I run this, my execution gets stuck at this codeblock ( I tried putting a print statement in the next line) when the response coming from the backend has header values, however if I send the response with no header from the backend (I am using django at the backend) then the my program runs with no issue.
So my question is how to handle responses with headers and how to extract them?
After a little researching I finally found the issue. My custom header name had space in it "New user" because of which http was not able to parse it. After changing the name to "newuser" everything is working fine.

JWT Signature with Request Body

I wanna create a Restful API using JWT with signature. The API only allows post method and there is request body in Json format. How do I add request Json body in JWT Signature?
https://localhost/Booking/Submit
JWT
.header {.alg="RS256"}
.payload { sender="ABC", recipient="XYZ", timestamp="010102020101010"}
.Signature {...}
Request Json body
{ "BookingId"=1, "BookingDate"="0404202001010", "BookedByName"="Mr. John", "BookedByContact"="12345678", "FacilitiyId"="10021"}
The JWT token is conventionally base64 encoded. This value is then added to your URL request as a header value for the “Authorization” key.
Your JSON payload is posted in the same URL request, except it makes up the body this time.

How to pass json in testing APIs using pytest

In falcon 1.1.0, the only way to send data is through body which takes byte data. How can we post json in such a situation using the simulate_post method while testing falcon APIs using pytest.
Use body to send JSON as a string:
data = json.dumps(data)
client.simulate_request(method='POST', path=url, body=data)
Optionally you can also set the content-type header to indicate it's a JSON request:
headers = {'Content-Type': 'application/json'}
data = json.dumps(data)
client.simulate_request(method='POST', path=url, headers=headers, body=data)

Authenticating into a REST API in parameters

I am trying to get a little bit familiar with this REST API:
https://docs.gemini.com/rest-api/#private-api-invocation
However, I am trying to figure out how they do authentication, and it seems they don't use OAuth. This is what they say:
Gemini uses API keys to allow access to private APIs. You can obtain these by logging on and creating a key in Settings/API. This will give you both an "API Key" that will serve as your user name, and an "API Secret" that you will use to sign messages.
All requests must contain a nonce, a number that will never be repeated and must increase between requests. This is to prevent an attacker who has captured a previous request from simply replaying that request. We recommend using a timestamp at millisecond or higher precision. The nonce need only be increasing with respect to the session that the message is on.
Now, I don't understand where to place my API Secret key. They don't really specify a parameter name for it. Same thing goes for the nonce. Also, does the nonce need to be randomized? And what size should the nonce be? I am not that familiar with this.
As described in the docs you linked you need to base64-encode the "request", "nonce" and "order_id" for the X_GEMINI_PAYLOAD header and SHA384 that payload with the API Secret for the X-GEMINI-SIGNATURE header.
Here's an example from the site (Python):
import requests
import base64
import hmac
from hashlib import sha384
url = "https://api.gemini.com/v1/order/status"
gemini_api_key = "mykey"
gemini_api_secret = "1234abcd"
# for the purposes of this example, we've shown hand-rolled JSON - please import json and use json.dumps in your real code!
b64 = base64.b64encode("""{
"request": "/v1/order/status",
"nonce": 123456,
"order_id": 18834
}
""")
signature = hmac.new("1234abcd", b64, hashlib.sha384).hexdigest()
headers = {
'Content-Type': "text/plain",
'Content-Length': "0",
'X-GEMINI-APIKEY': gemini_api_key,
'X-GEMINI-PAYLOAD': b64,
'X-GEMINI-SIGNATURE': signature,
'Cache-Control': "no-cache"
}
response = requests.request("POST", url, headers=headers)
print(response.text)