oAuth2.0在laravel5.2中的簡單應用

oAuth是一個關於受權的開放網絡標準,目前的版本是2.0laravelphp開發框架,目前最新穩定版本是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.json中的require

     

  • 執行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

     
    oauth數據表

     

  • 配置config/oauth2.phpgrant_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 INTOoauth_clients(id,secret,name,created_at) VALUES('shy7jf8fa93d59c45502c0ae8chj76s', 'bc7f6f8fa93d59c45502c0ae8c4a95d', '點餐系統', CURRENT_TIMESTAMP)來添加一個客戶端。ruby

     
    添加一個客戶端

     

  • 添加一個用戶
    執行php artisan make:auth後訪問http://localhost:8000/register註冊一個用戶。網絡

     
    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); 
 
測試結果

 
表oauth_access_tokens中數據

受權驗證

  • 建立一個獲取用戶列表的接口
// 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.phpApp\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,轉載請註明出處。

相關文章
相關標籤/搜索