(jwt+dingo)和(passport+dingo)使用

Laravel實現(xiàn)dingo+JWT api接口之配置篇
Laravel實現(xiàn)dingo+JWT api接口之實戰(zhàn)篇

  1. 安裝dingo

  2. 你需要修改你的 composer.json 文件,然后執(zhí)行 composer update 把最后一個版本的包加入你的項目
"require": {
    "dingo/api": "1.0.*@dev"
}

或者直接

composer require dingo/api:1.0.x@dev
  • 打開 config/app.php,注冊必要的 service provider 在你的應(yīng)用 providers 之前。
'providers' => [
    Dingo\Api\Provider\LaravelServiceProvider::class
]
  • 生成dingo配置文件 config/api.php :
php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
  • .env添加基礎(chǔ)配置(四個即可):
#標(biāo)準(zhǔn)樹
API_STANDARDS_TREE=vnd
#前綴
API_PREFIX=api
#版本
API_VERSION=v1
#開啟調(diào)試
API_DEBUG=true
phpAPI_STANDARDS_TREE=vnd
API_SUBTYPE=biubiujun
API_PREFIX=api
API_VERSION=v1
API_NAME=BiuBiuJun
API_CONDITIONAL_REQUEST=false
API_STRICT=false
API_DEFAULT_FORMAT=json
API_DEBUG=true
API_STANDARDS_TREE - API規(guī)格 
  1 本地或私有環(huán)境 
  2 prs 非商業(yè)銷售的項目 
  3 vnd 公開的以及商業(yè)銷售的項目
API_SUBTYPE - API簡稱 
API_PREFIX - API前綴(或使用API_DOMAIN - API子域名) 
API_VERSION - API默認(rèn)版本 
API_NAME - API名稱 
API_CONDITIONAL_REQUEST - 帶條件的請求,由于緩存API請求的時候會使用客戶端緩存功能,所以默認(rèn)開啟了帶條件的請求 
API_STRICT - 嚴(yán)格模式,要求客戶端發(fā)送Accept頭而不是默認(rèn)在配置文件中指定的版本 
API_DEFAULT_FORMAT - 響應(yīng)格式,默認(rèn)的響應(yīng)格式是JSON 
API_DEBUG - 調(diào)試模式
  1. 你需要修改你的 composer.json 文件,然后執(zhí)行 composer update 把最后一個版本的包加入你的項目
"require": {
    "tymon/jwt-auth": "0.5.*"
}

或者直接

composer require tymon/jwt-auth
  • 打開 config/app.php,注冊到 providers 數(shù)組。
'providers'=>[
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
]
  • 注冊jwt門面:
'aliases'=>[
'JWTAuth'=> Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory'=> Tymon\JWTAuth\Facades\JWTFactory::class,
]
  • 生成jwt配置文件 config/jwt.php :
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
  • 生成 jwt.php 文件中數(shù)組的 secret 鍵成對應(yīng)的值:
php artisan jwt:generate
  • 關(guān)聯(lián)dingo與JWT

修改 config/api.phpauth 如下:

'auth' => [  
    'basic' => function($app){  
        return new Dingo\Api\Auth\Provider\Basic($app['auth']);  
    },  
    'jwt' => function($app){  
        return new Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);  
    }  
],  
  • 安裝passport

    1. 使用 Composer 依賴包管理器安裝 Passport :
composer require laravel/passport
  • 接下來,將 Passport 的服務(wù)提供者注冊到配置文件 config/app.phpproviders 數(shù)組中:
    Laravel\Passport\PassportServiceProvider::class,
    Passport 使用服務(wù)提供者注冊內(nèi)部的數(shù)據(jù)庫遷移腳本目錄,所以上一步完成后,你需要更新你的數(shù)據(jù)庫結(jié)構(gòu)。Passport 的遷移腳本會自動創(chuàng)建應(yīng)用程序需要的客戶端數(shù)據(jù)表和令牌數(shù)據(jù)表:
  • php artisan migrate
    添加了如下幾張表:
Migrating: 2016_06_01_000001_create_oauth_auth_codes_table
Migrating: 2016_06_01_000002_create_oauth_access_tokens_table
Migrating: 2016_06_01_000003_create_oauth_refresh_tokens_table
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrating: 2016_06_01_000005_create_oauth_personal_access_clients_table

如果你不打算使用 Passport 的默認(rèn)遷移,你應(yīng)該在 AppServiceProviderregister 方法中調(diào)用 Passport :: ignoreMigrations 方法。 你可以導(dǎo)出這個默認(rèn)遷移用 php artisan vendor:publish --tag=passport-migrations 命令。

  1. 接下來,你需要運行 passport:install 命令來創(chuàng)建生成安全訪問令牌時用到的加密密鑰,同時,這條命令也會創(chuàng)建「私人訪問」客戶端「密碼授權(quán)」客戶端:【運行 passport:install 命令,該命令將會創(chuàng)建生成安全訪問令牌(token)所需的加密鍵,此外,該命令還會創(chuàng)建 personal accesspassword grant 客戶端用于生成訪問令牌,該命令會在 storage 目錄中生成認(rèn)證需要的加密鍵, oauth-private.keyoauth-public.key
    php artisan passport:install
    執(zhí)行上述代碼后的結(jié)果:
Encryption keys generated successfully.
Personal access client created successfully.
Client ID: 1
Client Secret: e7pPOyPMFiEuE5EvtDvY9qsesfTgqNhb61r37cez
Password grant client created successfully.
Client ID: 2
Client Secret: eI4XKieiDQRUCMpnfb3g5MOr8SItQ5rCZBv3bWO3
  • 上面命令執(zhí)行后,請將 Laravel\Passport\HasApiTokens Trait 添加到 App\User 模型中,這個 Trait 會給你的模型提供一些輔助函數(shù),用于檢查已認(rèn)證用戶的令牌和使用作用域:
<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
  • 接下來,需要在 AuthServiceProviderboot 方法中調(diào)用 Passport::routes 函數(shù)。這個函數(shù)會注冊一些在訪問令牌、客戶端、私人訪問令牌的發(fā)放和吊銷過程中會用到的必要路由:
<?php
namespace App\Providers;
use Carbon\Carbon;
use Laravel\Passport\Passport;
use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::tokensExpireIn(Carbon::now()->addDays(15));

        Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

        Passport::pruneRevokedTokens();
    }
}

最后,需要將配置文件 config/auth.phpapi 部分的授權(quán)保護(hù)項( driver )改為 passport 。此調(diào)整會讓你的應(yīng)用程序在接收到 API 的授權(quán)請求時使用 Passport 的 TokenGuard 來處理:

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'passport',
        'provider' => 'users',//【可能這里需要修改】
    ],
],
  • 如果用手機(jī)號進(jìn)行授權(quán)的話,需要修改模型
    /**
     * [findForPassport passport通過手機(jī)號/賬號驗證]
     * @param  [type] $username [description]
     * @return [type]           [description]
     */
    public function findForPassport($username)
    {
        // if (!$this->where('phone', $username)->first()) {
        //     return $this->where('name', $username)->first();
        // }
        // return true;

        return $this->where('phone', $username)->first();

        // return $this->where('phone', $username)->first() || $this->where('name', $username)->first();
    }
php artisan passport:client --password

配置Dingo使用Passport密碼發(fā)放令牌

  • 創(chuàng)建 PassportDingoProvider
php artisan make:provider PassportDingoProvider
  • 修改 app/Providers/PassportDingoProvider.php
<?php
namespace App\Providers;
use Dingo\Api\Routing\Route;
use Illuminate\Http\Request;
use Dingo\Api\Auth\Provider\Authorization;
class PassportDingoProvider extends Authorization
{
    public function authenticate(Request $request, Route $route)
    {
        return $request->user();
    }
    public function getAuthorizationMethod()
    {
        return 'bearer';
    }
}
  • 修改 config/api.php
'auth' => [ 
    'custom' => \App\Providers\PassportDingoProvider::class
],
  • 修改 App/Http/Kernel.php
protected $middlewareGroups = [
   ...
   'api:auth' => [
       'auth:api',
       'api.auth'
    ]
    ...
];
  • routes/api.php 修改之前注冊路由
$api = app('Dingo\Api\Routing\Router');
$api->version('v1', ['middleware' => 'api:auth', 'namespace' => 'App\Http\Controllers\Api\V1'], function ($api) {
    $api->get('user/{id}', 'UserController@show');
    $api->get('user', 'UserController@index');
});
  • 測試-請求令牌
    curl -d "username=biubiujun@163.com@password=123456@grant_type=password&client_id=<client_id>&client_secret=<client_secret>" http://localhost/path/public/api/oauth/token
  • 測試-請求用戶列表
curl -H "Authorization: Bearer <token>" http://localhost/path/public/api/user
composer require zircote/swagger-php
  • 創(chuàng)建 SwaggerController
php artisan make:controller SwaggerController
  • 修改 app/Http/Controller/SwaggerController
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
class SwaggerController extends Controller
{
    public function doc()
    {
        $swagger = \Swagger\scan(__DIR__ . '/../');
        return response()->json($swagger);
    }
}
  • 下載 swagger-ui
    swagger-ui
    • 將swagger-ui/dist目錄放入public/doc
    • 修改public/doc/index.html
<script src='lang/translator.js' type='text/javascript'></script>
<script src='lang/zh-cn.js' type='text/javascript'></script>
<script type="text/javascript">
    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
        if (url && url.length > 1) {
          url = decodeURIComponent(url[1]);
        } else {
          // url = "http://petstore.swagger.io/v2/swagger.json"
          url = "/api/doc";
        }

訪問http://localhost/path/public/doc/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,823評論 18 139
  • 前言 也可以關(guān)注我的個人博客 ?這里摘錄下laravel5.5教程的認(rèn)證文檔,做個總結(jié),方便今后查閱。 安裝pas...
    小峰書閱讀 2,103評論 0 1
  • 是什么 如果你知道yum、apt-get、npm、bower等命令中的一種或者多種,那么,你也能很快知道compo...
    旱魃一樣閱讀 3,151評論 0 9
  • Composer Repositories Composer源 Firegento - Magento模塊Comp...
    零一間閱讀 3,967評論 1 66
  • 我是易效能G130的學(xué)員袁斌,現(xiàn)在是G153: 2班5組的復(fù)訓(xùn)生。 我的三個標(biāo)簽: 1、我是一個25歲小孩的媽媽 ...
    自由飛翔呀閱讀 417評論 0 0