[TOC]
# API 認證
## 簡介
Laravel 提供一個簡單的基于令牌的身份驗證,但建議使用 [Laravel Passport](https://learnku.com/docs/laravel/5.8/passport) 來實現提供 API 身份驗證。
## 配置
```
// 創建遷移,在 users 表中添加列 api_token
// php artisan make:migration add_api_token_to_users_table --table=users
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->string('api_token', 80)->after('password')
->unique()
->nullable()
->default(null);
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('api_token');
});
}
// 創建后執行
$ php artisan migrate
```
令牌生成
```
// 在注冊控制器 RegisterController 的 create 方法中設置
// 此設置是以文本方式存儲在數據庫
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
/**
* 在有效注冊之后創建一個新用戶實例:
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'api_token' => Str::random(60),
]);
}
```
### 哈希令牌
```
// 配置 api_token 以 SHA-256 散列方式存儲數據庫
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => true,
],
```
### 生成哈希令牌
使用哈希令牌時, 你不應該在用戶注冊期間生成 API 令牌。 相反, 你需要在應用程序中實現自己的 API 令牌管理頁面。 這個頁面應該允許用戶初始化和刷新其 API 令牌。 當用戶發出初始化或者刷新令牌請求時,你應該在數據中存儲令牌的哈希副本,并將令牌的純文本副本返回到視圖 / 前端客戶端進行一次顯示。
例如,為給定用戶初始化 / 刷新令牌并將純文本令牌作為 JSON 響應返回的控制器方法可能如下所示:
```
// 需要新增頁面以處理哈希令牌的初始化與更新
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
class ApiTokenController extends Controller
{
/**
* 更新已經驗證過的用戶的 API 令牌。
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function update(Request $request)
{
$token = Str::random(60);
$request->user()->forceFill([
'api_token' => hash('sha256', $token),
])->save();
return ['token' => $token];
}
}
```
## 路由保護
```
// 測試鏈接:http://test.com/api/user?api_token=令牌
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/user', function(Request $request) {
return $request->user();
});
/*
* 設置請求頭部
* Content-Type: application/x-www-form-urlencoded
* X-Requested-With: XMLHttpRequest
* Authorization: Bearer 令牌
*
* 或者設置請求參數
* api_token: 令牌
*/
Route::middleware('auth:api')->post('/update', function () {
return ['data'=>'update'];
});
```
## 請求中傳遞令牌
例子使用 Guzzle HTTP 庫演示,可以根據應用程序的需要選擇其他請求方式。
```
// 鏈接參數
$response = $client->request('GET', '/api/user?api_token='.$token);
// 表單參數
$response = $client->request('POST', '/api/user', [
'headers' => [
'Accept' => 'application/json',
],
'form_params' => [
'api_token' => $token,
],
]);
// Bearer令牌,請求頭
$response = $client->request('POST', '/api/user', [
'headers' => [
'Authorization' => 'Bearer '.$token,
'Accept' => 'application/json',
],
]);
```
- 入門指南
- 安裝
- 部署
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 腳手架
- 編譯資源 Mix
- 安全相關
- 用戶認證
- API 認證
- 綜合話題
- 命令行
- 廣播
- 緩存
- 集合
- 事件
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 速查表
- Artisan
- Auth
- Blade
- Cache
- Collection
- Composer
- Config
- Container
- Cookie
- DB
- Environment
- Event
- File
- Helper
- Input
- Lang
- Log
- Model
- Pagination
- Queue
- Redirect
- Request
- Response
- Route
- SSH
- Schema
- Security
- Session
- Storage
- String
- URL
- UnitTest
- Validation
- View