[英]How to authorize rest api in php with Basic Authentication
我正在開發用於登錄的Rest API,但我無法正常工作,這意味着我可以從服務器獲取數據並將響應發送給用戶。 現在,我想用它實現基本的身份驗證。 我對Rest API開發和Slim非常陌生。 所以請幫助我。
$app->get('/users', function() use($app, $db)
{
$app->response()->header("Content-Type", "application/json");
$req=$app->request();
$pass = $req->params('pass'); // Getting parameter with names
$email = $req->params('email'); // Getting parameter with names
$user=$db->Sign_Up()->where (array('email_id'=>$email, 'password'=> $pass));
$data=$user->fetch();
$status=$data['status'];
$user_pass=$data['password'];
$user_email=$data['email_id'];
$user_name=$data['user_name'];
$uesr_ip=$_SERVER['REMOTE_ADDR'];
if ($pass!=$user_pass || $email != $user_email)
{
echo json_encode(
array(
'status'=>false,
'Message'=>'Email or Password dose not match.'
));
}
else if($status=='active')
{
$user_os = getOS();
$user_browser = getBrowser();
$message = "
<div style='font-size:15px;text-align:center;border: 1px solid #ddd;background: #DADADA;margin: 2%;padding: 5%;'>
Hi $user_name,
Your KarAssist Account $user_email was just used to sign in from $user_browser on $user_os.
</div>
";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$mail_sent=mail($user_email, "New Sign In from $user_browser on $user_os", $message,$headers);
if ($mail_sent)
{
echo json_encode(array(
'User_Info'=>array(
'status'=>true,
'id'=> $data['id'],
'First_Name'=>$data['first_name'],
'Email_Id'=>$data['email_id'],
'Last_Name'=>$data['last_name'],
'Phone_Number'=>$data['phone_number'],
'Status'=>$data['status']
),
'App_info'=>array(
'Device_token'=>$data['device_token'],
'App_version'=>$data['app_version']
)));
}
else
{
echo json_encode(array(
'status'=>false,
'message'=>"There is some Technical error. We are sorry to inform you we could not sent mail to you. So please change your mail ASAP."
));
}
}
else
{
echo json_encode(array(
'status'=>false,
'message'=>"User with Email $email is not avtivated yet."
));
}
});
該代碼運行良好。 我想用它實現基本身份驗證。 所以,讓我知道如何去做。
最簡單的方法是使用現有的Basic Auth中間件 。 使用此中間件,您可以執行以下操作:
$app = new \Slim\App;
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/api",
"realm" => "Protected",
"users" => [
"root" => "t00r",
"user" => "passw0rd"
]
]));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.