如何使用令牌调用API

时间:2016-10-15 22:11:42

标签: rest api laravel laravel-5.2

我在Laravel 5.2中使用https://github.com/Zizaco/entrust进行ReST API集成

我可以检索令牌。然后,我尝试将其传递给需要令牌的路径。但是我收到状态代码为401的错误:

  

由于凭据错误或授权标头无效而无法进行身份验证。

这是我使用的代码:

$base_url = 'http://mysite/api/';
$fields = array(
    'email' => urlencode('myEmail'),
    'password' => urlencode('myPass'),
);

$fields_string = '';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $base_url . 'login');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);
$result = json_decode($result, true);
$token = false;
if ($result['result'] == 'success') {
    $token = $result['token'];
}

if ($token) { //call the api by passing the token:
//    var_dump($token);
curl_setopt($ch,CURLOPT_URL, $base_url . 'admin/sells');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $token
]);
    curl_setopt($ch,CURLOPT_POST, null);
    curl_setopt($ch,CURLOPT_POSTFIELDS, null);
    curl_setopt($ch, CURLOPT_HTTPGET, 1);
// var_dump(curl_getinfo($ch));
    $result = curl_exec($ch);

    $result = json_decode($result, true);
    var_dump($result);
}

这是我的路线:

$api = app('Dingo\Api\Routing\Router');

$app_controller = 'App\\Http\\Controllers\\';
$auth_controller = 'App\\Http\\Controllers\\Auth\\';
$api->version('v1', function ($api) use ($app_controller,$auth_controller) {
    $api->post('login', ['as' => 'api_login', 'uses' => $auth_controller . 'AuthController@authenticate']);
});

$api->version('v1', ['middleware' => 'api.auth'], function ($api) use ($app_controller,$auth_controller) {
    $api->get('admin/sells', ['as' => 'api_admin_sells', 'uses' => $app_controller . 'SellsController@apiIndex']);
});

我做错了吗?

0 个答案:

没有答案