Laravel API TOKEN身份验证无效

时间:2017-12-10 17:32:40

标签: authentication laravel-5 oauth-2.0 laravel-passport laravel-socialite

我正在尝试使用api authentication token对用户进行身份验证。但即使使用了正确的令牌之后,也就是未经授

我正在使用laravel auth和socialite进行社交认证 所以我的api.php路线就像这样

Route::group(['middleware'=>'auth:api'], function(){
  Route::get('hello','ApiTestControler@index');
});

    我试图用这个URL访问它

http://localhost:8000/api/hello 并在标题

token: TOKEN HERE 
Content-Type: application/json 
Accept: application/json

我希望它能够登录并显示ApiTestController index methord

但它抛出一个错误401 unauthorized 如何解决此问题并使用API​​令牌进行用户身份验证?

我的控制器

 class ApiTestController extends Controller
{
  public function index(){
    return json_encode ("Welcome REST API");
  }
}

用户迁移表

        $table->increments('id');
        $table->string('name')->unique();
        $table->string('first_name')->nullable();
        $table->string('last_name')->nullable();
        $table->string('email')->unique()->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->boolean('activated')->default(false);
        $table->string('token');
        $table->ipAddress('signup_ip_address')->nullable();
        $table->ipAddress('signup_confirmation_ip_address')->nullable();
        $table->ipAddress('signup_sm_ip_address')->nullable();
        $table->ipAddress('admin_ip_address')->nullable();
        $table->ipAddress('updated_ip_address')->nullable();
        $table->ipAddress('deleted_ip_address')->nullable();
        $table->timestamps();
        $table->softDeletes();

config\auth.php

中的身份验证配置
'guards' => [
        'web' => [
            'driver'   => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver'   => 'token',
            'provider' => 'users',
        ],
      ]

1 个答案:

答案 0 :(得分:3)

我发现它唯一可能导致问题的是数据库中token列的名称,它应该是api_token,因此将迁移更改为:

$table->increments('id');
$table->string('name')->unique();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->string('email')->unique()->nullable();
$table->string('password');
$table->rememberToken();
$table->boolean('activated')->default(false);
$table->string('api_token', 60)->unique();     //<-- this one here
$table->ipAddress('signup_ip_address')->nullable();
$table->ipAddress('signup_confirmation_ip_address')->nullable();
$table->ipAddress('signup_sm_ip_address')->nullable();
$table->ipAddress('admin_ip_address')->nullable();
$table->ipAddress('updated_ip_address')->nullable();
$table->ipAddress('deleted_ip_address')->nullable();
$table->timestamps();
$table->softDeletes();

不要忘记刷新数据库,还有一件事要获得必须使用的经过身份验证的用户:

Auth::guard('api')->user()

而不是:

Auth::user()