Autorization using bearer token failing - swift

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.

Related

Flutter post request headers do not appear on Google Cloud Function

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..

Dio dart/Flutter get and set cookie

I would like to do a set cookies, do a get request and after get the cookies.
In python it will be this:
> import requests cookies = {'status': 'working','color':'blue'}
> response = session.get('https://google.com/', cookies=cookies)
> print(session.cookies.get_dict())
Do you know how to flutter it? I tried something like this but it doesn't seem to have a cookie in the response and the cookie doesn't seem to be sent
Map<String, String> headers = {
"status":"working",
"color":"blue"
};
final BaseOptions dioBaseOptions = BaseOptions(
baseUrl: 'https://google.com',
headers: {
'Cookie': headers,
},
);
dio = Dio(dioBaseOptions);
var cookieJar=CookieJar();
dio.interceptors.add(CookieManager(cookieJar));
var response = await dio.get('https://google.com/');
Cookie is set by a server in a response header and a browser sends it back in a request header.
After receiving an HTTP request, a server can send one or more Set-Cookie headers with the response. The browser usually stores the cookie and sends it with requests made to the same server inside a Cookie HTTP header.
See Using HTTP cookies for details.
CookieManager does this for dio and Flutter.
To access Cookies in a dio response
final cookies = response.headers['set-cookie']

what is the correct way to pass Bearer token in header section of my HTTP.Post in 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.

Flutter HTTP calls using authorization fails but works in postman

I am using Flutter 1.20.4, http 0.12.2 package and I am having an issue where my HTTP calls are successful in Postman but fail in a flutter. I came across a number of articles talking about issue with lower case HTTP headers and some older servers. I don't have that issue as I have tested postman with lower case. I have checked my bearer token on jwt.io and issuer matches the domain I am using. Any call made from flutter that uses authorization will return as "not authenticated" so it would come up with HTTP 302 (redirect to login by identity provider). Any ideas?
My code looks like this:
import 'package:http/http.dart' as http;
...
var getProfileUrl = _identityApi + '/api/profile/get'; // TODO: CHANGE THIS
var accessToken = await _secureStorage.read(key: 'bearerToken');
var response = await http.get(getProfileUrl, headers: {
HttpHeaders.contentTypeHeader: 'application/json',
HttpHeaders.acceptHeader: 'application/json',
HttpHeaders.authorizationHeader: 'Bearer $accessToken'
});
POSTMAN:
FLUTTER:
try this
import 'package:http/http.dart' as http;
...
Map<String,String> _headers={
'content-type': 'application/json',
'accept: 'application/json',
'authorization': 'Bearer $accessToken'
};
var getProfileUrl = _identityApi + '/api/profile/get'; // TODO: CHANGE THIS
var accessToken = await _secureStorage.read(key: 'bearerToken');
var response = await http.get(getProfileUrl, headers: _headers);

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.