'Authentication Api using user name and password in flutter web
I try to authenticate api using user name and password it worked good in flutter android app but in flutter web do not get any data
below my authentication function in php api and api connect file and flutter code
I have pass some headers to api like Access-Control-Allow-Origin, Content-Type, Access-Control-Allow-Headers, Authorization,
In php side
function checkAuthenticate()
{
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
if ($_SERVER['PHP_AUTH_USER'] != "aaaa" || $_SERVER['PHP_AUTH_PW'] != "aaaa12345"){
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Page Not Found';
exit;
}
} else {
exit;
}
}
// in connect file
<?php
$dsn = "mysql:host=localhost;dbname=id18" ;
$user = "id18" ;
$pass = "" ;
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8"
);
try {
$con = new PDO($dsn , $user , $pass , $option);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,
Access-Control-Allow-Origin");
header("Access-Control-Allow-Methods: POST, OPTIONS , GET");
include "functions.php";
checkAuthenticate() ;
}catch(PDOException $e) {
echo $e->getMessage() ;
}
?>
In flutter side
List<PatientModel> productsResponseFromJson(String str) =>
List<PatientModel>.from(
json.decode(str).map((x) => PatientModel.fromJson(x)));
Future<List<PatientModel>> fetchProducts() async {
final response = await http
.get(Uri.parse(ApiPath.All_Pat)
,headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": "true", // Required for cookies, authorization headers with HTTPS
"Access-Control-Allow-Headers": "Origin,Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,locale",
"Access-Control-Allow-Methods": "POST, OPTIONS, GET",
'authorization': 'Basic ' + base64Encode(utf8.encode('aaaa:aaaa12345')),
}
);
var data = response.body;
return productsResponseFromJson(data);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|