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

個人github博客:zgxxx.github.io/php

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

參考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,其實新版本不須要。git

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 ,個人配置是github

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

還需在命令行執行 php artisan jwt:secret,會在.env自動添加JWT_SECRET,其餘若須要,能夠到各類的配置文件中看,在.env添加便可web

4. 關鍵處理

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

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

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

這裏須要把api本來的driver => session 改成使用jwt機制,provider對應你要用的用戶認證表,通常就是登陸註冊那張表json

<?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…api

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, ];session

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');app

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

相關文章
相關標籤/搜索