安裝套件cmd執行以下composer require laravel/passport
在config/app.php
檔案中到providers
配置文件數組中註冊 Passport 服務
Passport 服務提供者在框架中註冊了自己的數據庫遷移目錄
所以要進行migratephp artisan migrate
create "personal access" and "password grant"php artisan passport:install
加入身份驗證防護選項
到config\auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
註冊頒發訪問令牌和撤銷訪問令牌、客戶端和個人訪問令牌所需的路由
到app\Providers\AuthServiceProvider.php
public function boot()
{
$this->registerPolicies();
Passport::routes(); // 加上
}
app\Models\User.php
use Laravel\Passport\HasApiTokens;
use HasApiTokens, HasFactory, Notifiable;
php artisan make:controller AuthController.php
新增登入登出及註冊function
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class AuthController extends Controller
{
public function signup(Request $request)
{
$validateData = $request->all();
$user = new User([
'name' => $validateData['name'],
'email' => $validateData['email'],
'password' => bcrypt($validateData['password']),
]);
$user->save();
return response('success', 201);
}
public function login(Request $request)
{
$validateData = $request->validate([
'email' => 'required|string|email',
'password' => 'required|string'
]);
if (!Auth::attempt($validateData)){
return response('授權失敗', 401);
}
$user = $request->user();
$tokenResult = $user->createToken('Token');
$tokenResult->token->save();
return response(['token'=> $tokenResult->accessToken]);
}
public function logout(Request $request)
{
$request->user()->token()->revoke();
return response(
["message" => "成功登出"]
);
}
}
到web.php
設定路由
Route::post('/signup', 'AuthController@signup'); // 註冊
Route::post('/login', 'AuthController@login'); // 登入
Route::group(['middleware'=>'auth:api'], function(){
Route::get('/logout', 'AuthController@logout');
});
首先註冊
註冊成功後登入取得token
將token複製到Bearer Token
複製完成後才能夠登出,登出後token就失效囉
可以舉一反三,將產品路由放置到auth路由內,這樣只有登入的人才可以取得產品資訊