Laravel5.4 Api Token认证

本片文章,我们将使用前后端分离的 API token 认证机制,使用Token可以解决API的无状态认证机制。

问题

api.php中接口使用中间件 middleware('auth:api')权限验证会出现问题:

Laravel5.4 Api Token认证

// 请求Api url
Route::post('question/follower', function(Request $request){
    $followed = \App\Models\Follow::where('question_id', $request->get('question'))
                 ->where('user_id', $request->get('user'))
                 ->count();
    if($followed)
    {
        return response()->json(['followed' => true]);
    }
   return response()->json(['followed' => false]);
})->middleware('auth:api');

根据错误提示,需要给api接口进行权限的验证,具体步骤可看下边:

一、给用户表users增加api_token字段

php artisan make:migration add_api_token_to_users --table=users

Created Migration: 2017_03_21_235545_add_api_token_to_users

在生成的迁移文件中添加字段:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddApiTokenToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('api_token', 64)->unique();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['api_token']);
        });
    }
}

然后使用下面的命令将字段添加到表中:

php artisan migrate

Laravel5.4 Api Token认证

二、用户注册时,需生成一个api_token

App\Http\Controllers\Auth\RegisterController.php文件的创建用户中添加 api_token 字段;

/**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data)
    {
        $user =  User::create([
            'name'     => $data['name'],
            'email'    => $data['email'],
            'avatar'   => '/images/avatars/default.png',
            'phone'    => '',
            'confirmation_token' => str_random(40),
            'password' => bcrypt($data['password']),
            'api_token' => str_random(60),   // api_token认证
        ]);

        $this->sendVerifyEmailTo($user);

        return $user;
    }

最后,不要忘记在 App\User.php用户模型表中的 $fillable 属性当中添加api_token字段:

/**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','avatar','confirmation_token','phone','api_token'
    ];

三、使用

有关token认证的原理,我们可以看该目录下的底层方法:
vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.php

1.重写resource\assets\js\bootstrap.js认证方法:

/*
  // API token 认证-【20170321】
window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'X-Requested-With': 'XMLHttpRequest'
};
*/
window.axios.defaults.headers.common = {
    'X-CSRF-TOKEN': window.Laravel.csrfToken,
    'Authorization': window.Laravel.apiToken
};

2. app.blade.php中增加api_token 判断

<!-- Scripts -->
    <script>
        window.Laravel = {!! json_encode([
            'csrfToken' => csrf_token(),
        ]) !!};

        Laravel.apiToken = "{{ Auth::check() ? 'Bearer '.Auth::user()->api_token : 'Bearer ' }}";
    </script>

相关文章:
Laravel 的 API 认证系统 Passport
Laravel5.4 Vue 框架中 X-CSRF-TOKEN 的两种设置方法
【日常填坑】之ajax请求laravel的api接口

相关推荐