Laravel API Token 體驗

xjpeng發表於2017-10-17

適用laravel版本5.3+

簡介

Laravel API 預設驅動為token,文件上沒介紹如何使用,下面讓我們來實現它。

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

配置欄位

專案下執行命令php artisan make:migration update_users_table_for_api_token --table=users生成遷移檔案.

修改遷移檔案

    /**
     * Run the migrations.
     *
     * @return void
     */
  public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            //欄位名固定,長度建議32以上
            $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執行遷移。資料表users會新增api_token欄位

配置模型

新增api_tokenUser模型$fillable$hidden屬性

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

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token','api_token'
    ];

生成api_token

程式碼放在註冊控制器app/Http/Controllers/Auth/RegisterController.php裡面。

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return \App\User
     */
    protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
            'api_token' =>str_random(64)
        ]);
    }

使用者註冊成功後自動分配一個api_token
file

配置API路由

routes/api.php裡面配置路由,使用token方式時一定要使用中介軟體auth:api
系統已經幫我們配置了一個Api路由,我們可以直接使用這個路由測試。

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

通過api_token獲取使用者

  • 通過GETPOST傳送api_token欄位資料獲取使用者。
  • 通過header頭部傳送Authorization獲取使用者。
 //方式GuzzleHttp\Client
 //假如你的token為DntgHWoEanBSYeMv,為了顯示效果擷取了長度
 //GuzzleHttp\Client方式
    $guzzle = new GuzzleHttp\Client;
        $response = $guzzle->get('http://mysite/api/user', [
            'headers' => [
                'Authorization' => 'Bearer DntgHWoEanBSYeMv',
            ],
        ]);

        print_r( json_decode((string) $response->getBody(), true));
 //假如你的token為DntgHWoEanBSYeMv,為了顯示效果擷取了長度
//jQuery方式
    $.ajaxSetup({
        headers:{
                Authorization:'Bearer DntgHWoEanBSYeMv'
        }
    });

    $.get('http://yoursite.com/api/user').
    then(function(data) {
       console.log(data);
    });

//axios方式
axios.defaults.headers.common['Authorization'] = 'Bearer DntgHWoEanBSYeMv';

axios.get('http://yoursite.com/api/user')
  .then(function(response) {
       console.log(response.data);
    });

注意這裡有跨域問題,可以設定Access-Control-Allow系列header解決跨域問題,
也有現成的中介軟體barryvdh/laravel-cors可以使用。

[參考] https://segmentfault.com/a/1190000006215513

相關文章