首頁 >後端開發 >php教程 >laravel dingo/api新增jwt-auth認證

laravel dingo/api新增jwt-auth認證

不言
不言原創
2018-07-09 09:48:543182瀏覽

這篇文章主要介紹了關於laravel dingo/api添加jwt-auth認證,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

前面我們學了laravel dingo /api創建簡單的api,這樣api是開放給所有人的,如何查看和限制api的呼叫呢?可以用jwt-auth來驗證,JSON Web Token Authentication

  1,先安裝jwt-auth插件,在命令列中用composer安裝

#
composer require tymon/jwt-auth '0.5.*'

  2,然後發佈

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"

  在/config/產生了一個jwt.php檔案

#  3,生成key

php artisan jwt:generate

  如果指令無法執行,可以在/config/jwt.php檔案中修改changeme為自己設定的密匙

#
'secret' => env('JWT_SECRET', 'changeme'),

  4,修改/app/Api/Controllers/HelloController.php為

<?php

namespace App\Api\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//添加jwt-auth认证
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class HelloController extends Controller
{
    public function index()
    {
        return &#39;{content:Helloworld!}&#39;;
    }
//添加jwt-auth认证
  	public function authenticate(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only(&#39;email&#39;, &#39;password&#39;);

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json([&#39;error&#39; => &#39;invalid_credentials&#39;], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json([&#39;error&#39; => &#39;could_not_create_token&#39;], 500);
        }

        // all good so return the token
        return response()->json(compact(&#39;token&#39;));
    }
}

  5,新增路由(/routes/web .php)

$api->post(&#39;auth&#39;, &#39;App\Api\Controllers\HelloController@authenticate&#39;);

  6,測試路由:php artisan api:routes,如果出現如下提示表示正確

#  訪問url:***.com/api/auth顯示錯誤,因為沒加token

重新修改hellocontrol和loutes

<?php

namespace App\Api\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class HelloController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return &#39;{content:Helloworld!}&#39;;
    }
  	public function authenticate(Request $request)
    {
        // grab credentials from the request
        $credentials = $request->only(&#39;email&#39;, &#39;password&#39;);

        try {
            // attempt to verify the credentials and create a token for the user
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json([&#39;error&#39; => &#39;invalid_credentials&#39;], 401);
            }
        } catch (JWTException $e) {
            // something went wrong whilst attempting to encode the token
            return response()->json([&#39;error&#39; => &#39;could_not_create_token&#39;], 500);
        }

        // all good so return the token
        return response()->json(compact(&#39;token&#39;));
    }
  //添加user
  	public function user()
    {
      JWTAuth::parseToken();
      $user = JWTAuth::parseToken()->authenticate();
      return $user;
    }
}

name('home');

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', function ($api) {
    $api->get('helloworld', 'App\Api\Controllers\HelloController@index');
  $api->post(&#39;auth&#39;, &#39;App\Api\Controllers\HelloController@authenticate&#39;);
  $api->get('auth', 'App\Api\Controllers\HelloController@user');
});

  用Google瀏覽器postman外掛程式取得token,注意是post方法,步驟如下圖所示

  將取得的token複製,貼到第二步驟的用戶驗證token中,下圖5中就是我們剛註冊的用戶

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

 Laravel5.5中利用Passport實作Auth認證的方法講解

Laravel框架中composer自動載入的實現詳解

以上是laravel dingo/api新增jwt-auth認證的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn