Flutter Web : How to send bearer token? - flutter

I have an ASP.Net Core web api that accepts bearer token (jwt) and I send this token in my Flutter with Android emulator without any problem with this code :
final response = await get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
But when I run this in Chrome browser the api response is : 405 Method Not Allowed .
What's the problem ?
UPDATE :
According to #anirudh comment I have enabled CROS in my web Api and problem have changed . Now the response is : 204 No Content

use http plugin
And do http.get and not just get
import 'package:http/http.dart' as http;
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});

Thanks to #anirudh I solved my problem
First defining a variable :
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
Then write these codes in my api in ConfigureServices :
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost") //Or my flutter web host
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed((host) => true);
});
});
and this line in Configure :
app.UseCors(MyAllowSpecificOrigins);

String token = await Candidate().getToken();
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
print('Token : ${token}');
print(response);

Related

When I use flutter http library with headers authorization token, its shows 500, in console. but in postman all okay

Here is my code, I also tried using retrofit but I failed and it shows 500 and "message": "Undefined index: token". but in postman, it shows 200. how can it be possible?
Also tried
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
Future getCertificateList() async {
final url = Uri.parse(
'https://portal-api.jomakhata.com/api/getCertificateList');
final response = await http.get(url,
headers: {
'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiY',
},
);
print(response.statusCode);
print(response.body);
return response.body;
}
In my console it's print 500
this is postman request image
try this code:
Future getCertificateList() async {
final uri = Uri.https('https://portal-api.jomakhata.com','/api/getCertificateList');
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader:
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI4NjE0MDcyLCJleHAiOjE2Mjg3MDA0NzIsIm5iZiI6MTYyODYxNDA3MiwianRpIjoiRnRjaGllbTFFdVlsYXZidyJ9.O24U0XGFiZdfXRGUP5xYD82-LisSbMsCtVZnuG6iTiYv',
HttpHeaders.contentTypeHeader: 'application/json',
});
print(response.statusCode);
print(response.body);
return response.body;
}

How can I make an http POST request from dart with authentication?

I'm trying to do a post, to create a user, but in a simple way. I do need to use authentication, so I'm passing the token in the header, as I would do in the GET request. But I'm not sure why I'm receiving the error "400 - Bad Request".
import 'package:http/http.dart';
{...}
Future test() async {
Response response = await post('https://access.altaviu.com/Data/api/Account/Register',
body: jsonEncode({
"Email": "useruser#gmail.com",
"Password": "QWERTY1234!",
"ConfirmPassword": "QWERTY1234!",
}),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${UserAccountData.token}',
});
if (response.statusCode == 200) {
print('SUCCESSFUL TEST');
} else {
print('ERROR IN THE TEST ${response.statusCode} - ${response.reasonPhrase}');
}
}
I'm using the library (or package) "http: 0.12.0+2"

How can I add request header automatically using http package

Currently I'm sending header with every request like as follow which is very repetitive.
Is there any process so that all my request will have a request header automatically ?
Or how can I avoid code repetition for the following lines:
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String token = sharedPreferences.getString('accessToken');
headers: {
'Contet-type': 'application/json',
'Authorization': 'Bearer $token',
}
My complete API Request code:
Future<http.Response> getAUser(userId) async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
String token = sharedPreferences.getString('accessToken');
return await http.get(
'$baseUrl/user/$userId/',
headers: {
'Contet-type': 'application/json',
'Authorization': 'Bearer $token',
},
).timeout(Duration(seconds: 30));
}
Yes you can centralize the headers in a separate class!
class BaseService {
Map<String, String> baseHeaders;
Future initBaseService() async {
final preferences = await SharedPreferences.getInstance();
baseHeaders= {
"Accept": "application/json",
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Bearer ${preferences.getString("TOKEN")}",
};
}
}
And then, you can inherit your class with the base class to have access to these methods.
class UserService extends BaseService {
Future<http.Response> getAUser(userId) async {
await initBaseService();
return await http
.get(
'$baseUrl/user/$userId/',
headers: baseHeaders,
)
.timeout(Duration(seconds: 30));
}
}

How to get User's followers using spotify sdk in flutter?

String authToken=await getAuthenticationToken();
final response = await http.get('https://api.spotify.com/v1/me/following', headers: {
'Authorization': 'Bearer $authToken',
});
print('Token: ${authToken}');
print(response.body);
I am getting an error:
Insufficent client scope

How to send parameters in headers using http package in flutter

I want to sent my auth-key in headers using http package but unfortunately its not working kindly help me .
var url = "https://paysafemoney.com/psmApi/Psm/userDashboard";
var response = await http.post(
url,
headers: {
"auth-key": LoginConfirmActivity.authKey,
},
body: sendLoginData,
);
print("Response = ${response.body}");
You can do like this
var fullUrl = '$stripeBaseUrl$customerId/sources?source=$cardToken';
var header = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': stripeKey,
};
final response = await client.post(fullUrl, headers: header);