我正在使用RESTful控制器属性构建一个带有laravel的RESTful api.到目前为止,我已经能够使大部分工作.现在的问题是验证,我试图使用“user_id”和“签名”的亚马逊方法.
我使用PHP的’hash_hmac()’创建签名.
我使用PHP的’hash_hmac()’创建签名.
这是一个api控制器的例子
class Api_Tasks_Controller extends Api_Controller { public $restful = true; public function get_index($id = null) { $this->verfiy_request(); if(!is_null($id)) { return Response::json(array("tasks"=>"just one"),200); } else { return Response::json(array("tasks"=>"everthing"),200); } } }
这是api控制器类
class Api_Controller extends Controller { public function verify_request() { //user id $user_id = (int) Input::get('user_id'); //signature $sig = Input::get('sig'); //Lookup user $user = Sentry::user($user_id); if($user) { //user email $email = $user->email; //user api key $api_key = $user->Metadata['api_key']; //recreate signature $_sig = hash_hmac("sha256",$email.$user_id,$api_key); if($_sig === $sig) { return Response::json(array("message"=>"Request Ok"),200); } else { return Response::json(array("message"=>"Request Bad"),400); } } else { return Response::json(array("message"=>"Request not authorized"),401); } }
发出获取请求http://api.xyz.com/v1/tasks/1?user_id=1\u0026amp;sig=41295da38eadfa56189b041a022c6ae0fdcbcd5e65c83f0e9aa0e6fbae666cd8即使在我更改了user_id参数的值时也会返回成功的消息,该参数应使签名无效请求无效.
似乎我的verfiy_request方法没有执行.
请帮帮我
我最近也在研究这个问题,并建议使用过滤器.它可以像这样工作:
原文链接:https://www.f2er.com/laravel/137849.htmlclass Api_Tasks_Controller extends Base_Controller { public $restful = true; function __construct() { // Check if user is authorized $this->filter('before','api_checkauth'); } // rest of the class .... }
Route::filter('api_checkauth',function() { //user id $user_id = (int) Input::get('user_id'); //signature $sig = Input::get('sig'); try { //Lookup user $user = Sentry::user($user_id); if($user) { //user email $email = $user->email; //user api key $api_key = $user->Metadata['api_key']; //recreate signature $_sig = hash_hmac("sha256",$api_key); if($_sig === $sig) { return Response::json(array("message"=>"Request Ok"),200); } else { return Response::json(array("message"=>"Request Bad"),400); } } else { return Response::json(array("message"=>"Request not authorized"),401); } } catch (Sentry\SentryException $e) { $errors = $e->getMessage(); // catch errors such as user not existing or bad fields return Response::json(array("message"=>$errors),404); } });
另外,谢谢你介绍我哨兵:-)