Laravel5.4 Api Token認證

本片文章,咱們將使用先後端分離的 API token 認證機制,使用Token能夠解決API的無狀態認證機制。php

問題

api.php中接口使用中間件 middleware('auth:api')權限驗證會出現問題:vue

clipboard.png

// 請求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接口進行權限的驗證,具體步驟可看下邊:ios

1、給用戶表users增長api_token字段

php artisan make:migration add_api_token_to_users --table=users

Created Migration: 2017_03_21_235545_add_api_token_to_userslaravel

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

<?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']);
        });
    }
}

而後使用下面的命令將字段添加到表中:json

php artisan migrate

clipboard.png

2、用戶註冊時,需生成一個api_token

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

/**
     * 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字段:axios

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

3、使用

有關token認證的原理,咱們能夠看該目錄下的底層方法:
vendor\laravel\framework\src\Illuminate\Auth\TokenGuard.phpsegmentfault

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接口後端

相關文章
相關標籤/搜索