oAuth
是一个关于授权的开放网络标准,目前的版本是2.0
。laravel
是php
开发框架,目前最新稳定版本是5.5
。授权在应用程序中有非常广泛的使用场景,本文将以laravel5.2
为例来简单介绍oAuth2.0
具体应用方案。
构建和配置项目
安装
laravel5.2
composer create-project laravel/laravel blog 5.2.*
没有composer
的同学需要先进行安装,具体可参考ubuntu16.04安装composer一文。-
修改
composer.json
在require
中添加"lucadegasperi/oauth2-server-laravel": "5.1.*"
composer.json中的require 执行
composer update
完成lucadegasperi/oauth2-server-laravel
的安装修改
config/app.php
在aliases
中添加'Authorizer' => LucaDegasperi\OAuth2Server\Facades\Authorizer::class,
在providers
中添加如下内容:
LucaDegasperi\OAuth2Server\Storage\FluentStorageServiceProvider::class,
LucaDegasperi\OAuth2Server\OAuth2ServerServiceProvider::class,
- 修改
app/Http/Kernel.php
在$middlewareGroups['web']
中添加\LucaDegasperi\OAuth2Server\Middleware\OAuthExceptionHandlerMiddleware::class,
并去掉\App\Http\Middleware\VerifyCsrfToken::class,
在$routeMiddleware
中添加如下内容:
'oauth' => \LucaDegasperi\OAuth2Server\Middleware\OAuthMiddleware::class,
'oauth-user' => \LucaDegasperi\OAuth2Server\Middleware\OAuthUserOwnerMiddleware::class,
'oauth-client' => \LucaDegasperi\OAuth2Server\Middleware\OAuthClientOwnerMiddleware::class,
'check-authorization-params' => \LucaDegasperi\OAuth2Server\Middleware\CheckAuthCodeRequestMiddleware::class,
'csrf' => App\Http\Middleware\VerifyCsrfToken::class,
执行
php artisan vendor:publish
这将生成config/oauth2.php
和数据库迁移所需的文件-
配置
.env
中数据库的连接信息并执行php artisan migrate
将得到以下数据表:oauth数据表 配置
config/oauth2.php
的grant_types
元素如下
'password' => [
'class' => '\League\OAuth2\Server\Grant\PasswordGrant',
'callback' => '\App\Http\Controllers\Auth\PasswordGrantVerifier@verify',
'access_token_ttl' => 3600
]
- 创建
\App\Http\Controllers\Auth\PasswordGrantVerifier.php
并填充内容如下
<?php
namespace App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Auth;
class PasswordGrantVerifier
{
public function verify($username, $password)
{
$credentials = [
'email' => $username,
'password' => $password,
];
if (Auth::once($credentials)) {
return Auth::user()->id;
}
return false;
}
}
- 在
app\Http\routes.php
中添加如下路由
Route::post('oauth/access_token', function() {
return Response::json(Authorizer::issueAccessToken());
});
获取授权
-
添加一个客户端
数据表oauth_clients
用于存储客户端信息,可通过语句INSERT INTO
oauth_clients(
id,
secret,
name,
created_at) VALUES('shy7jf8fa93d59c45502c0ae8chj76s', 'bc7f6f8fa93d59c45502c0ae8c4a95d', '点餐系统', CURRENT_TIMESTAMP)
来添加一个客户端。添加一个客户端 -
添加一个用户
执行php artisan make:auth
后访问http://localhost:8000/register
注册一个用户。register一个用户 测试授权服务
测试代码和结果如下:
function post($url, $param){
$oCurl = curl_init();
$aPOST = [];
foreach($param as $key=>$val){
$aPOST[] = $key.'='.urlencode($val);
}
$strPOST = join('&', $aPOST);
curl_setopt($oCurl, CURLOPT_URL, $url);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($oCurl, CURLOPT_POST,true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
$sContent = curl_exec($oCurl);
$aStatus = curl_getinfo($oCurl);
curl_close($oCurl);
if(200 == intval($aStatus['http_code'])){
return $sContent;
}else{
return false;
}
}
$server = 'http://localhost:8000/oauth/access_token';
$params = [
'grant_type' => 'password',
'username' => 'admin@admin.com',
'password' => '123456',
'client_id' => 'shy7jf8fa93d59c45502c0ae8chj76s',
'client_secret' => 'bc7f6f8fa93d59c45502c0ae8c4a95d',
];
echo post($server, $params);
授权验证
- 创建一个获取用户列表的接口
// app/Http/routes.php中增加路由
Route::group(['prefix'=>'api', 'middleware' => 'oauth'], function () { // 加上'middleware' => 'oauth'将会进行oAuth2.0验证
Route::get('/user', 'Api\UserController@index');
});
<?php
// App\Http\Controllers\Api\UserController.php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\User;
use Response;
class UserController extends Controller
{
public function index()
{
return Response::json(User::all());
}
}
-
访问用户列表接口
不带access_token访问带不正确或过期的access_token访问带正确的access_token访问 获取授权用户信息
需要修改app/Http/routes.php
和App\Http\Controllers\Api\UserController.php
,具体修改内容如下:
// 在用户路由组中增加Route::get('/user/show', 'Api\UserController@show');
Route::group(['prefix'=>'api', 'middleware' => 'oauth'], function () { // 加上'middleware' => 'oauth'将会进行oAuth2.0验证
Route::get('/user', 'Api\UserController@index');
Route::get('/user/info', 'Api\UserController@info');
});
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\User;
use Response;
use LucaDegasperi\OAuth2Server\Authorizer;
class UserController extends Controller
{
public function index()
{
return Response::json(User::all());
}
public function info(Authorizer $authorizer)
{
$user_id = $authorizer->getResourceOwnerId();
return Response::json(User::find($user_id));
}
}
本文首发于公众号:programmer_cc,转载请注明出处。