Laravel5.5+dingo+JWT 開發後臺 API

自行腦補發表於2018-11-08

我的github部落格:zgxxx.github.io/

dingo api 中文文件: www.bookstack.cn/read/dingo-… Laravel中使用JWT:laravel-china.org/articles/10… 輔助文章: www.jianshu.com/p/62b0c4d75…

參考https://www.jianshu.com/p/62b0c4d75e59 這篇文章基本就能搭建出環境,我使用的版本跟他一樣 "dingo/api": "2.0.0-alpha1","tymon/jwt-auth": "^1.0.0-rc.1",不知道別的版本有啥大的區別,但是網上找的其他一些文章使用的是舊的版本,jwt封裝的東西路徑可能不一樣,可能會保錯,有些文件還說要手動新增Tymon\JWTAuth\Providers\LaravelServiceProvider::class和Dingo\Api\Provider\LaravelServiceProvider::class,其實新版本不需要。

1. composer.json引入包,執行composer update:

  "require": {
	......
    "dingo/api": "2.0.0-alpha1",
    "tymon/jwt-auth": "^1.0.0-rc.1"
  },
複製程式碼

2. 執行下面兩個語句自動生成dingo和jwt的配置檔案:

php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"
//config資料夾中生成dingo配置檔案---> api.php
複製程式碼
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
//config資料夾中生成dingo配置檔案---> jwt.php
複製程式碼

3. 配置 .env

具體配置可參考 文件https://www.bookstack.cn/read/dingo-api-wiki-zh/Configuration.md ,我的配置是

API_STANDARDS_TREE=vnd
API_PREFIX=api
API_VERSION=v1
API_DEBUG=true
API_SUBTYPE=myapp 
複製程式碼

還需在命令列執行 php artisan jwt:secret,會在.env自動新增JWT_SECRET,其他若需要,可以到各種的配置檔案中看,在.env新增即可

4. 關鍵處理

'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

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

        'api' => [
            'driver' => 'jwt', 
            'provider' => 'users',
        ],
    ],
複製程式碼

這裡需要把api原本的driver => session 改為使用jwt機制,provider對應你要用的使用者認證表,一般就是登入註冊那張表

<?php

namespace App\Models;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject {
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'unionid'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];


    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims() {
        return [];
    }
}
複製程式碼

5. 設定控制器

考慮到可能後面需要開發不同版本api,所以在app/Http/Controller下建立了V1,V2目錄,根據你自己的需求來,只要寫好名稱空間就ok

avatar

<?php
/**
 * Date: 17/10/12
 * Time: 01:07
 */

namespace App\Http\Controllers\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use App\User;

class AuthController extends Controller
{

    protected $guard = 'api';//設定使用guard為api選項驗證,請檢視config/auth.php的guards設定項,重要!

    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('refresh', ['except' => ['login','register']]);
    }

    public function test(){
        echo "test!!";
    }

    public function register(Request $request)
    {

        $rules = [
            'name' => ['required'],
            'email' => ['required'],
            'password' => ['required', 'min:6', 'max:16'],
        ];

        $payload = $request->only('name', 'email', 'password');
        $validator = Validator::make($payload, $rules);

        // 驗證格式
        if ($validator->fails()) {
            return $this->response->array(['error' => $validator->errors()]);
        }

        // 建立使用者
        $result = User::create([
            'name' => $payload['name'],
            'email' => $payload['email'],
            'password' => bcrypt($payload['password']),
        ]);

        if ($result) {
            return $this->response->array(['success' => '建立使用者成功']);
        } else {
            return $this->response->array(['error' => '建立使用者失敗']);
        }

    }

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');

        if ($token = $this->guard()->attempt($credentials)) {
            return $this->respondWithToken($token);
        }

        return $this->response->errorUnauthorized('登入失敗');
    }

    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        //return response()->json($this->guard()->user());
        return $this->response->array($this->guard()->user());
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();

        //return response()->json(['message' => 'Successfully logged out']);
        return $this->response->array(['message' => '退出成功']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard($this->guard);
    }
}
複製程式碼

控制器中名稱空間namespace需要設定好,路由的時候需要用到, $this->middleware('refresh', ['except' => ['login','register']]); 這裡的中介軟體使用的是網上找的,用於無痛重新整理jwt的token,具體可以參考這篇文章:www.jianshu.com/p/9e95a5f8a…

6. refresh中介軟體

<?php

namespace App\Http\Middleware;

use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

class RefreshToken extends BaseMiddleware
{
    /**
     * @author: zhaogx
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
     * @throws JWTException
     */
    public function handle($request, Closure $next)
    {
        // 檢查此次請求中是否帶有 token,如果沒有則丟擲異常。
        $this->checkForToken($request);

        // 使用 try 包裹,以捕捉 token 過期所丟擲的 TokenExpiredException  異常
        try {
            // 檢測使用者的登入狀態,如果正常則通過
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            throw new UnauthorizedHttpException('jwt-auth', '未登入');
        } catch (TokenExpiredException $exception) {
            // 此處捕獲到了 token 過期所丟擲的 TokenExpiredException 異常,我們在這裡需要做的是重新整理該使用者的 token 並將它新增到響應頭中
            try {
                // 重新整理使用者的 token
                $token = $this->auth->refresh();
                // 使用一次性登入以保證此次請求的成功
                \Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
            } catch (JWTException $exception) {
                // 如果捕獲到此異常,即代表 refresh 也過期了,使用者無法重新整理令牌,需要重新登入。
                throw new UnauthorizedHttpException('jwt-auth', $exception->getMessage());
            }
        }

        return $next($request)->withHeaders([
                'Authorization'=> 'Bearer '.$token,
            ]);
    }
}
複製程式碼

寫好中介軟體後需要在app/Http/Kernel.php中注入 protected $routeMiddleware = [ ​ ...... ​ 'refresh' => RefreshToken::class, ];

7. routes/api.php 設定路由

$api = app('Dingo\Api\Routing\Router');
$api->version('v1', ['namespace' => 'App\Http\Controllers\V1'], function ($api) {
    $api->post('register', 'AuthController@register');
    $api->post('login', 'AuthController@login');
    $api->post('logout', 'AuthController@logout');
    $api->post('refresh', 'AuthController@refresh');
    $api->post('me', 'AuthController@me');
    $api->get('test', 'AuthController@test');
});
複製程式碼

這裡有個坑,不要這樣寫api->post('me',['middleware' =>'refresh'], 'AuthController@me');
這樣雖然能執行這個中介軟體但執行到next(request)這裡會出錯,貌似是一個回撥報錯 Function name must be a string ,不太清楚具體原因,可以這樣寫api->post('me',, 'AuthController@me')->middleware('refresh');

根據以上幾個步驟就可以建立起簡單的api後臺基礎,獲取api路由列表可以使用命令列: php artisan api:routes routes:list貌似無法顯示以上api路由,需要在api.php那裡再寫一遍原始的laravel路由定義才可以顯示:比如這樣Route::post('api/test', 'AuthController@test');後續會用另一篇幅來記錄postman和小程式相關知識

相關文章