laravel 使用guzzlehttp/guzzle 配置步骤
1、安装 guzzlehttp/guzzle#
通过 Composer 包管理器安装 guzzlehttp/guzzle
composer require guzzlehttp/guzzle
2、安装 laravel/passport#
通过 Composer 包管理器安装 Passport
composer require laravel/passport
3、配置 config/auth.php#
3、1 修改看守器
修改之前
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
'hash' => false,
],
],
修改之后
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
],
3、2 添加 app\Providers\AuthServiceProvider
修改之前
public function boot()
{
$this->registerPolicies();
}
修改之后
public function boot()
{
$this->registerPolicies();
//passport 注册发出访问令牌并撤销访问令牌、客户端和个人访问令牌所必需的路由
Passport::routes();
//令牌有效期
Passport::tokensExpireIn(now()->addDays(15));
//刷新令牌的令牌有效期
Passport::refreshTokensExpireIn(now()->addDays(30));
//个人令牌有效期
Passport::personalAccessTokensExpireIn(now()->addMonths(6));
}
3、3 模型配置
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Laravel\Passport\HasApiTokens;
use Modules\Common\Entities\Authenticatable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasFactory;
use HasApiTokens;
use HasRoles;
use HasFactory;
}
4、安装#
php artisan passport:install
生成记录存放在数据表 oauth_clients
中
5、oauth/token 请求#
Route::get('/auth/callback', function (Request $request) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://laravel55.dev/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => '2', // oauth_clients 的ID
'client_secret' => 'tBxbskNg9fJTIh0Ufk4eKdpneSkLx1H5HxGy2VTk', // oauth_clients secret
'redirect_uri' => 'http://laravel55.dev/auth/callback',
'code' => $request->code,
],
]);
return json_decode((string) $response->getBody(), true);
});
注意:password_client 字段值必须是 1,provider 的值是看守器,必须对于 config/auth.php 文件 guards =》【web=》provider】的值#
'guards' => [
'web' => [
'provider' => 'users',
],
'api' => [
'provider' => 'users',
],
],
passport:client 命令#
创建客户端最简单的方式就是使用 Artisan 命令 passport:client,该命令可用于创建你自己的客户端以方便测试 OAuth2 功能。当你运行 client 命令时,Passport 会提示你输入更多关于客户端的信息,并且为你生成 client ID 和 secret
php artisan passport:client
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: