Flutter Desktop Auth - flutter

As we all know desktop application has no auth support so any one can help me with this.
Future<http.Response> signUp(
String email,
String password,
) async {
final uri =
Uri.parse("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=$apiKey");
final headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer token',
};
Map<String, dynamic> body = {
"email": "xyz23#gmail.com",
"password": "password",
"returnSecureToken":true,
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
http.Response response = await http.post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
print(response.statusCode);
print(response.body);
jsonResponse = json.decode(response.body);
// box.write("token", jsonResponse['refreshToken']);
// oneTimeToken = jsonResponse['refreshToken'];
// print(oneTimeToken);
if (box.read('token') != null) {
Fluttertoast.showToast(
msg: 'Account Created Successfully',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);;setState(() {
loading = false;
});
} else if (response.statusCode != 200) {
setState(() {
loading = false;
});
Fluttertoast.showToast(
msg: 'Account Already existing \n or missing data',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
return response;
}
Error:
flutter: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Invalid Credentials",
"domain": "global",
"reason": "authError",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED",
"metadata": {
"method": "google.cloud.identitytoolkit.v1.AuthenticationService.SignInWithPassword",
"service": "identitytoolkit.googleapis.com"
}
}
]
}
}
I am having this error can any one tell me what is this (OAuth 2 access token).I used this code on mongodb Works fine.
or
if anyone have any other solution it will be big help if provided.
thankyou.
get solution for flutter desktop auth.

Assuming you are NOT using OAuth 2.0 for your API, remove the authorization header from your sign up request and it should work.
final headers = {
'Content-Type': 'application/json',
//Remove this 'Authorization': 'Bearer token',
};
Try it out on the command line using your API key
curl --request POST \
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[YOUR_API_KEY]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"email":"test#test.com","password":"password123"}' \
--compressed
https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts/signUp
https://support.google.com/googleapi/answer/6158862?hl=en&ref_topic=7013279
https://support.google.com/googleapi/answer/6158849?hl=en&ref_topic=7013279
https://developers.google.com/identity/protocols/OAuth2#libraries

Related

Why not displaying card

I want to intigrate stripe payment but i got this error
** FlowController must be successfully initialized using configureWithPaymentIntent() or configureWithSetupIntent() before calling presentPaymentOptions()**
How solve this error also it is not displaying any card
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email,amount: 50.0);
},
child: Text("Pay20\$"),
),
),
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body); Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Zohaib',
));
await Stripe.instance.presentPaymentSheet();
Fluttertoast.showToast(
msg: "payment successfully",
);
}
catch(e){
if (e is StripeException) {
Fluttertoast.showToast(
msg: "Stripe error $e",
);
}
Fluttertoast.showToast(
msg: "$e",
toastLength: Toast.LENGTH_SHORT, );
}
}
You need to create the PaymentIntent on the server-side and not within your flutter app.
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
Instead of calling the Stripe API directly as you did in the code above, you should call your own API and generate a Payment Intent and just send the client_secret to your flutter App, otherwise you would be exposing your secret key and thus giving access to your data. This is described here.
Once you do this server-side part the rest is explained here.

Flutter Dio NO_RENEGOTIATION(ssl_lib.cc:1725) error 268435638

I have a problem when I make a http request to the server
when I post on flutter it returns NO_RENEGOTIATION(ssl_lib.cc:1725) error 268435638 error, but when I try to use postman it works fine.
I've equated all the headers with postman, replaced Jcenter() with MavenCentral() and it doesn't work
This is the code I use:
final Map<String, dynamic> requestData = {
"email": Encryption().encryptKey(email),
"password": Encryption().encryptKey(password),
"user_ad": userType,
"token_fcm": _tokenFcm,
"is_encrypted": true,
};
Response response = await _dio.post(
"$basePath/login",
data: FormData.fromMap(requestData),
options: Options(
headers: {
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Host": "btnsmartdev.btn.co.id",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
"Content-Length": "173"
},
validateStatus: (status) {
print("INI STATUS");
print(status);
return (status ?? 0) < 500;
},
followRedirects: false,
)
);
final data = response.data;
Here's what I get in terminal:
Here's the request from postman:

get data from one API that is dependent on another API flutter

Hello friends I am learning to build apps in Flutter. it's a single screen must display data from second api using user_id value from the first api.I have api response from server like this :
{
"code": 0,
"message": "",
"data": [
{
"userbox_id": 7,
"user_id": 53,
"box_id": 55,
"status": 0,
"created_at": "2021-04-28T11:55:12.000000Z",
"updated_at": "2021-04-28T11:55:12.000000Z"
},
{
"userbox_id": 8,
"user_id": 53,
"box_id": 56,
"status": 0,
"created_at": "2021-04-29T10:29:43.000000Z",
"updated_at": "2021-04-29T10:29:43.000000Z"
},
"error": [],
"status": 200
}
I would like to use "user_id" value to fetch data from second API response .
How i can do that ?
the first method:
Future<List<ActiveBox>> fetchBoxes() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_ALL_BOXES);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
// print(response.statusCode);
var body = jsonDecode(response.body);
print(body);
List<ActiveBox> boxes = [];
for (var item in body['data']) {
boxes.add(ActiveBox.fromJson(item));
}
print(boxes);
inspect(boxes);
return boxes;
and the second method :
Future<User> getUser() async {
SharedPreferences localStorage = await SharedPreferences.getInstance();
String token = localStorage.getString('access_token');
print(token);
await checkInternet();
Map<String, String> headers = {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
};
var url = Uri.parse(ApiUtil.GET_USER);
var response = await http.get(url, headers: headers);
switch (response.statusCode) {
case 200:
var body = jsonDecode(response.body);
User users = User.fromJson(body);
return users;
how i can implement that ? any help please

How to convert cURL -X -u, -H, -d to http post in Flutter

I am facing problem while converting cURL to flutter http post.
Below is the cURL code available
curl -X POST url
-u <YOUR_KEY_ID>:<YOUR_SECRET>
-H 'content-type:application/json'
-d '{ "amount": 50000, "currency": "INR", "receipt": "rcptid_11"}'
Below is the code that I have rewritten in flutter with the help of flutter documentaion.
Future<Album> createAlbum() async{
final response = await http.post(
Uri.parse('url'),
headers: {
HttpHeaders.authorizationHeader: '<$_key>:<$_secretKey>',
HttpHeaders.contentTypeHeader: 'application/json',
},
body: jsonEncode(<String, String>{
"amount": (amount*100).toString(),
"currency": "INR",
"receipt": date,
}),
);
if (response.statusCode == 201) {
print('Success');
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');
}
}
All the parameters are defined in the class and used in createAlbum method. http post fails to send data.
Thanks!
You need to base64 encode the basic auth and put the string Basic before the user:password:
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$_key:$_secretKey'));
Then use this for the auth header:
// ...
HttpHeaders.authorizationHeader: basicAuth,

Issue with uploading multi part image file with dio in Flutter

I used Dio framework to upload image to server in my flutter app. Dio version 3.0.9.
Post method.
Added 4 headers
Created form data with image and other fields.
I have analysed many more methods. Like degrading Dio to 2.3.1, to use UploadFileInfo method. Not a success. Then with multipartfileupload. Finally this one.
Future<bool> createStoreWithDio() async {
Map<String, String> headers = {
"Accept": "application/json",
"authorization": tokenString,
"authtype": "admin",
"Content-Type": "multipart/form-data"
};
try {
FormData formData = new FormData.fromMap({
"logo": await http.MultipartFile.fromPath("logo", imageFile.path,
contentType: new MediaType('image', 'png')),
"name": " Bala ios",
"description": "_description",
"website": "www.website.com",
"password": "Test password",
"user_name": "Test userInformationName",
"mobile": "9988776655",
"email": "test#techit.io",
});
print(formData.fields);
Response response = await dio
.post(
"API",
data: formData,
options: Options(
headers: headers,
),
)
.then((value) {
print(value.toString());
});
print(response.toString());
} catch (error) {
print(error);
}
}
imageFile is the file I captured from camera/ gallery.
I am getting 500 exception. Any help would be helpful
I am not sure what caused this,this code is used in an app i have change based on your code,but i am not sending any headers so you need to add then try with this code let me know it it's work for you.also make sure you have file imageFile.path also your api url is correct or not
make sure you have imported
`'import package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';`
Dio dio = new Dio();
final mimeTypeData =
lookupMimeType(imageFile.path, headerBytes: [0xFF, 0xD8]).split('/');
FormData formData = FormData.fromMap({
"name": " Bala ios",
"description": "_description",
"website": "www.website.com",
"password": "Test password",
"user_name": "Test userInformationName",
"mobile": "9988776655",
"email": "test#techit.io",
"logo": await MultipartFile.fromFile(imageFile.path,
contentType: MediaType(mimeTypeData[0], mimeTypeData[1])),
});
var response = await dio.post(
Urls.ImageInsert,
data: formData,
);
var message = response.data['message'];