Access Token有两种类型,分别是Bearer类型和MAC类型
入口文件中替换原生 Request 为 BaseRequest // 使得 request 和 response 都是 json 格式
class BaseRequest extends Request
{
public function expectsJson()
{
return true;
}
public function wantsJson()
{
return true;
}
}
composer require laravel/passport
// 生成加密 access_token 的 key、密码授权客户端、个人访问客户端,其中password grant client是这次要用的
php artisan passport:install
Laravel\Passport\HasApiTokens Trait 添加到 App\User 模型中 // 提供一些辅助函数检查已认证用户的令牌和使用范围
use HasApiTokens, Notifiable;
// 用于表单伪造
composer require guzzlehttp/guzzle
// config/auth.php
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
Passport::tokensExpireIn(now()->addDays(15)); // access_token 过期时间
Passport::refreshTokensExpireIn(now()->addDays(60)); // refresh_token 过期时间
// routes/api.php
Route::post('/oauth/token', '\Laravel\Passport\Http\Controllers\AccessTokenController@issueToken');
Route::post('/register', 'PassportController@register');
Route::post('/login', 'PassportController@login');
Route::post('/refresh', 'PassportController@refresh');
Route::post('/logout', 'PassportController@logout');
Route::get('test', function () {
return 'ok';
})->middleware('auth');
namespace App\Http\Controllers;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PassportController extends Controller
{
protected $clientId;
protected $clientSecret;
public function __construct()
{
$this->middleware('auth')->except('login', 'register', 'refresh');
// 从password grant client取值
$client = \Cache::remember('password_client', 60 * 5, function () {
return \DB::table('oauth_clients')->where('id', 3)->first();
});
$this->clientId = $client->id;
$this->clientSecret = $client->secret;
}
protected function username()
{
return 'email';
}
public function register()
{
$this->validator(request()->all())->validate();
$this->create(request()->all());
return $this->getToken();
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255', 'unique:users',],
'email' => ['required', 'string', 'email', 'max:255',],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::forceCreate([
'name' => $data['name'],
'email' => $data['email'],
'password' => password_hash($data['password'], PASSWORD_DEFAULT),
]);
}
// public function logout(Request $request)
// {
// auth()->user()->token()->revoke(); // 只会使 access_token 失效
//
// return ['message' => '退出登录成功'];
// }
public function logout()
{
$tokenModel = auth()->user()->token();
$tokenModel->update([
'revoked' => 1,
]);
\DB::table('oauth_refresh_tokens')
->where(['access_token_id' => $tokenModel->id])->update([
'revoked' => 1,
]);
return ['message' => '退出登录成功'];
}
public function login()
{
$user = User::where($this->username(), request($this->username()))
->firstOrFail();
if (!password_verify(request('password'), $user->password)) {
return response()->json(['error' => '抱歉,账号名或者密码错误!'],
403);
}
return $this->getToken();
}
public function refresh()
{
$response = (new Client())->post('http://mushishi.com/api/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => request('refresh_token'),
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'scope' => '*',
],
]);
return $response->getBody();
}
/**
* @param Request $request
* @param Client $guzzle
*
* @return \Psr\Http\Message\ResponseInterface
*/
private function getToken()
{
$response = (new Client())->post('http://mushishi.com/api/oauth/token', [
'form_params' => [
'grant_type' => 'password',
'username' => request('email'),
'password' => request('password'),
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'scope' => '*',
],
]);
return $response->getBody();
}
}
因为返回的access_token是Bearer类型,所以使用postman的时候,测试test方法的时候,测试方法是这样的
此外,refresh的refresh_token参数传递方法如图
先注册作用范围
// AppServiceProvider的register()中 注册 scope
Passport::tokensCan([
// 范围名称和描述
'test1' => 'for test1',
'test2' => 'for test2',
]);
注册中间件
// app/Http/Kernel.php的$routeMiddleware中注册中间件
'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class, // and
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class, // or
Route::get('test', function () {
return 'ok';
})->middleware('scope:test1'); // 其访问范围是test1,可以访问
当'scope' => 'test1'
时,
Route::get('test', function () {
return 'ok';
})->middleware('scope:test2'); // 其访问范围是test2,不可以访问
【scopes:test1,test2】代表范围是test1且test2 // and
【scope:test1,test2】代表范围是test1或test2 // or
当'scope' => 'test1'
时,
Route::get('test', function () {
return 'ok';
})->middleware('scopes:test1,test2'); // 其访问范围是test1 and test2,不可以访问
当'scope' => 'test1'
时,
Route::get('test', function () {
return 'ok';
})->middleware('scope:test1,test2'); // 其访问范围是test1 or test2,可以访问
部分scope相关函数
// 以注册的Scope
Laravel\Passport\Passport::scopeIds(); // ["test1","test2"]
// 以注册的所有Scope以及其描述
Laravel\Passport\Passport::scopes(); // [{"id":"test1","description":"for test1"},{"id":"test2","description":"for test2"}]
// 返回特定的已注册的Scope以及其描述
Laravel\Passport\Passport::scopesFor(['test1', 'check-status']); // [{"id":"test1","description":"for test1"}]
// 判断范围是否存在
Laravel\Passport\Passport::hasScope('place-orders'); // false