官方文档:https://docs.golaravel.com/docs/5.5/passport/
Laravel使用Laravel Passport轻松实现API身份验证,Laravel Passport在几分钟内就可以为Laravel应用程序提供完整的OAuth2服务器实现
composer安装
composer require laravel/passport
不过很多时候因为php版本的原因无法安装,就需要在composer.json
--require
中添加
"laravel/passport": "4.0.3"
然后
composer update
接下来,将 Passport 的服务提供者注册到配置文件 config/app.php 的 providers 数组中:
Laravel\Passport\PassportServiceProvider::class,
在mysql中创建存储客户端和访问令牌所需的table
php artisan migrate
创建生成安全访问令牌时所需的加密密钥,和用于生成访问令牌的「个人访问」客户端和「密码授权」客户端:
php artisan passport:install
建议将生成的令牌令牌写入.env中,如下
CLIENT_ID=1
CLIENT_SECRET=oSXGS6cu7xAB6gIF05p57itujd2ieyRPatZOsbJl
PASSPORT_CLIENT_ID=2
PASSPORT_CLIENT_SECRET=wYFO2jTAu5IcOHS0pbYTiLrM0M1XmWAPUDYXnOhr
在 Laravel\Passport\HasApiTokens
引入HasApiTokens
,用于检查已认证用户的令牌和使用范围
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
}
接下来,在 AuthServiceProvider
的 boot
方法中调用 Passport::routes
函数。这个函数会注册发出访问令牌并撤销访问令牌、客户端和个人访问令牌所必需的路由
<?php
namespace App\Providers;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* 应用程序的策略映射。
*
* @var array
*/
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
最后,将配置文件 config/auth.php
中授权看守器 guards
的 api
的 driver
选项改为 passport
。此调整会让你的应用程序在在验证传入的 API 的请求时使用 Passport 的 TokenGuard
来处理:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
默认情况下,Passport 发放的访问令牌是永久有效的,不需要刷新。在 AuthServiceProvider
的 boot
方法中配置有效期
use Carbon\Carbon;
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Passport::routes();
Passport::tokensExpireIn(Carbon::now()->addDays(15));
Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
开始使用
登录后台代码,这里使用了guzzlehttp/guzzle
HTTP客户端包
composer require guzzlehttp/guzzle
public function login(){
$email=\request('email');
$password =\request('password');
if (auth()->attempt(['email'=>$email,'password'=>$password])){
$user = User::where('email',$email)->first();
$name = is_null($user) ? '' : $user->name;
return $this->proxy('password',$name,[
'username'=> $email,
'password'=> $password,
'scope'=> '',
]);
}
return response()->json([
'code'=> 501,
'message'=>'账号密码错误'
]);
}
public function proxy($grantType, $name, array $data = []){
$data = array_merge($data,[
'client_id' => env('PASSPORT_CLIENT_ID'),
'client_secret' => env('PASSPORT_CLIENT_SECRET'),
'grant_type'=>$grantType
]);
$url = 'http://'.$_SERVER["HTTP_HOST"].'/oauth/token';
$http = new GuzzleHttp\Client();
$http->request('POST',$url,[
'verify' => false,
'form_params' => $data
]);
$token = json_decode(( string) $response->getBody(),true);
return response()->json([
'code' => 1,
'data' => [
'token' => $token['access_token'],
'expires_in' => $token['expires_in'],
'user'=>$name
]
])->cookie('refreshToken',$token['refresh_token'],14000,null,null,false,true);
}
登录成功会返回token
,expires_in
,user
以及存入cookie中的refreshToken
当调用 Passport 保护下的路由时,接入的 API 应用需要将访问令牌作为 Bearer
令牌放在请求头 Authorization
中。例如
$response = $client->request('GET', '/api/user', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
api.php
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/posts','Auth\PostController@index')->middleware('auth:api');