Laravel集成dingo+jwt

Dingo

Dingo是一个composer的包,能够用于创建自己想要的API,返回JSON数据

官方文档

Dingo安装与配置

关于JWT-auth的安装参考Laravel-JWT

修改composer.json文件,在require中添加:

“dingo/api”:”2.0.0-alpha1”

然后命令行执行:

composer update

发布配置文件:

php artisan vendor:publish –provider=”Dingo\Api\Provider\LaravelServiceProvider”

修改config/auth.php:

  • 修改defaultsguards为:

    ‘guard’=>’api’

  • guards中添加:

`api` => [
    'driver' => 'jwt',
    'provider' => 'users',
],
  • providers中,修改users为:
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\ModelName::class,//ModelName为自己定义的模型名
    ],
]
  • 集成jwt和dingo:在app\Provider\AppServiceProvider.php中的boot方法中添加jwt扩展:
public function boot() {
    app('Dingo\Api\Auth')->extend('jwt',function($app){
        return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
    });
}
  • 修改config\api.php:
'auth' => [
    'jwt' => 'Dingo\Api\Auth\Provider\JWT',
],
  • config\app.phpprovider添加:
Dingo\Api\Provider\LaravelServiceProvider::class,
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
  • 配置.env文件
API_PREFIX=api
API_STANDARS_TREE=vnd
API_VERSION=v1
API_DEBUG=true

关于.env文件的配置,参考(https://github.com/dingo/api/wiki/Configuration)

使用Dingo

路由创建Api

在测试时需要设置Authorization类型为Bearer token

修改routes/api.php

<?php

$api = app("Dingo\Api\Routing\Router");
$api->version('v1',function($api) {
    $api->group(["namespace" => "App\Http\Controllers\Api",'middleware'=>'auth:api'],function($api){
        //此处定义的api需要先经过jwt认证
        //访问链接为yourServerName/api/decode
        //Controller、method为自己定义的关联模型对应的控制器和方法

        $api->post('decode','Controller@method');
    });
    $api->group(["namespace" => "App\Http\Controllers\Api"],function($api){
        //在这里写的api不需要经过jwt认证
        $api->post('login','Controller@method');
    });
});

创建控制器

<?php

namespace App\Http\Controllers;


use App\Account;
use Tymon\JWTAuth\JWTAuth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Resources\Json\JsonResource;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Translation\Tests\Dumper\JsonFileDumperTest;


class AccountController extends BaseController
{
    protected $jwt;
    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

    public function register(Request $request)
    {
        $account = New Account;
        $account->email = $request->input('email');
        $account->password = Hash::make($request->input('password'));
        if($account->save()){
            return "注册成功";
        }
    }

    public function login(Request $request)
    {
        $this->validate($request, [
            'email'    => 'required|email|max:255',
            'password' => 'required',
        ]);
        try {
            //验证用户是否存在,存在则颁发token,不存在,则不颁发token。
            if (! $token = $this->jwt->attempt($request->only('email', 'password'))) {

                return response()->json(['user_not_found'], 404);
            }
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            return response()->json(['token_expired'], 500);
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return response()->json(['token_invalid'], 500);
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            return response()->json(['token_absent' => $e->getMessage()], 500);
        }

        return JsonResponse::create([
            'success'=>'200',
            'msg'=>'ok',
            'data'=>[
                'user'=>Auth::user(),
                'token'=>$token
            ]
        ]);
    }

    /*测试方法*/
    public function decode(Request $request){
        return response()->json(["测试成功"],200); 
    }
}