交流群 375462817
视频教程 https://space.bilibili.com/476513143
授权码模式
- 哔哩哔哩提供一个“微信登陆”的链接,用户点击跳转到微信授权服务器。
- 用户根据微信授权服务器提示登陆微信并确认授权给哔哩哔哩。
- 微信授权服务器返回用户代理(浏览器)一个授权码。
- 用户代理(浏览器)把这个授权码传给哔哩哔哩。
- 哔哩哔哩凭借授权码向微信授权服务器请求令牌。
- 微信授权服务器发送令牌给哔哩哔哩。
服务器端(微信)
配置
composer create-project --prefer-dist laravel/laravel laravel6
.env 数据库配置
修改数据库默认字符串长度
composer require laravel/passport
Laravel\Passport\HasApiTokens Trait 添加到 App\User 模型中 // 提供一些辅助函数检查已认证用户的令牌和使用范围
安装前端必备的东西(脚手架)
下载 node https://nodejs.org/en/
composer require laravel/ui
php artisan ui vue --auth
npm install cnpm -g --registry=https://registry.npm.taobao.org
cnpm install
cnpm run prod
composer require guzzlehttp/guzzle // 伪造 http 请求
// config/auth.php
'api' => [
'driver' => 'passport',
'provider' => 'users',
'hash' => false,
],
php artisan migrate // 创建表来存储客户端和 access_token 等
php artisan passport:keys // 加密生成的 access_token
// 注册路由 AuthServiceProvider
Passport::routes();
Passport::tokensExpireIn(now()->addDays(15)); // access_token 过期时间
Passport::refreshTokensExpireIn(now()->addDays(60)); // refresh_token 过期时间
创建客户端
php artisan passport:client
第三方应用程序(bilibili)
准备
composer create-project --prefer-dist laravel/laravel laravel6
composer require guzzlehttp/guzzle // 伪造 http 请求
web.php
session()->put('state', $state = Str::random(40));
$query = http_build_query([
'client_id' => $clientId,
'redirect_uri' => 'http://bili.com/auth/callback',
'response_type' => 'code',
'scope' => '*',
'state' => $state,
]);
return redirect('http://lishen.com/oauth/authorize?'.$query);
});
// 回调地址,获取 code,并随后发出获取 token 请求
Route::view('/auth/callback', 'auth_callback');
Route::post('/get/token', function (\Illuminate\Http\Request $request) use (
$clientId,
$clientSecret
) {
// csrf 攻击处理
$state = $request->session()->pull('state');
throw_unless(
strlen($state) > 0 && $state === $request->params['state'],
InvalidArgumentException::class
);
$response
= (new \GuzzleHttp\Client())->post('http://lishen.com/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => $clientId,
'client_secret' => $clientSecret,
'redirect_uri' => 'http://bili.com/auth/callback',
'code' => $request->params['code'],
],
]);
return json_decode((string)$response->getBody(), true);
});
// 刷新 token
Route::view('/refresh/page', 'refresh_page');
Route::post('/refresh', function (\Illuminate\Http\Request $request) use (
$clientId,
$clientSecret
) {
$http = new GuzzleHttp\Client;
$response = $http->post('http://lishen.com/oauth/token', [
'form_params' => [
'grant_type' => 'refresh_token',
'refresh_token' => $request->params['refresh_token'],
'client_id' => $clientId,
'client_secret' => $clientSecret,
],
]);
return json_decode((string)$response->getBody(), true);
});
refresh_page
auth_callback.blade.php