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一文。

  • 修改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.phpgrant_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 INTOoauth_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);
 
测试结果

 
表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,转载请注明出处。

posted on 2018-02-13 20:13 mikeccn 阅读(...) 评论(...) 编辑 收藏

导航

公告