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一文。php
修改composer.json
在 require
中添加"lucadegasperi/oauth2-server-laravel": "5.1.*"
laravel
執行composer update
完成lucadegasperi/oauth2-server-laravel
的安裝web
修改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
和數據庫遷移所需的文件json
配置.env
中數據庫的鏈接信息並執行php artisan migrate
將獲得如下數據表:ubuntu
配置config/oauth2.php
的grant_types
元素以下api
'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)
來添加一個客戶端。ruby
添加一個用戶
執行php artisan make:auth
後訪問http://localhost:8000/register
註冊一個用戶。網絡
測試受權服務
測試代碼和結果以下:app
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()); } }
訪問用戶列表接口
獲取受權用戶信息
須要修改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,轉載請註明出處。