I'm facing some issues in Flutter REST API using with JWT token
Here the header authentication was not passing properly. But it working good in Postman
**Example Code:**
String url = "project URL";
String token = "generated jwt token";
var headers = {
'Authorization': token,
'Cookie': 'ci_session=u17u9effeqk5fdhl1eqdh4jsmu3o3v29'
};
var request = http.Request('GET', Uri.parse(url));
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
If I try without the JWT token by removing it in the backend it's working properly. But I need to work with JWT.
Can anyone please help to fix this issue?
CodePudding user response:
I use dio package to work with the same...
// Import dio package
Future<void> function() async {
Dio dio = new Dio();
String url = 'example.com';
try {
final response = await dio.post(
url,
options: Options(
headers: {'Authorization': 'Bearer $userToken'}, //This is where you define your header and provide jwt token
),
);
} on DioError catch (error) {
if (error.response!.statusCode == 401) {
print(error.response.toString());
throw Error();
}
print(error);
throw Error();
}
}
}
The package can be found here https://pub.dev/packages/dio
Feel free to clear up any confusions
CodePudding user response:
The most likely issue here is the value that you give in your header.
For Bearer tokens, the value given in the Authorization header must be Bearer
followed by the value of your token. If you did not implement some specific/homemade authorisation function in your backend, this must be what is expected to be received.
Try replacing 'Authorization': token,
by
'Authorization': `Bearer $token`,
and it shouldd work as intended.