laravel中使用jwt+dingo搭建api接口认证_用户认证

本人的环境:laravel5.8、centos7.3、php7.1.3

1、在composer.json中require下加入

    "tymon/jwt-auth": "1.0.*@dev",
    "dingo/api": "^2.3"

2、项目跟目录执行 composer update安装

安装成功后

3、发布配置文件

    # 这条命令会在 config 下增加一个 jwt.php 的配置文件
    php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
    # 这条命令会在 config 下增加一个 api.php 的配置文件
    php artisan vendor:publish --provider="Dingo\Api\Provider\LaravelServiceProvider"

4、 生成jwt秘钥

php artisan jwt:secret

5、路由api文件修改:routes/api.php

$api = app("Dingo\Api\Routing\Router");
$api->version('v1', function ($api) {
    $api->group(["namespace" => "App\Http\Controllers\Api",'middleware'=>'jwt.auth'], function ($api) {
        //之后在这里写api
        $api->post('decode', 'Accounts@decode');
    });
    $api->group(["namespace" => "App\Http\Controllers\Api"], function ($api) {
        //之后在这里写api
        $api->post('login', 'Accounts@login');
    });
});

6、创建Base文件

<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Dingo\Api\Routing\Helpers;
use App\Http\Controllers\Controller;

class Base extends Controller
{
    //
    use Helpers;

    /****
     * BaseController constructor.
     */
    public function __construct()
    {

    }
}

7、添加Account模型

<?php
namespace App;

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

class Account extends Authuser implements JWTSubject
{
    use Notifiable;

    protected $hidden = ['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(); /*自己可以定义的生成token的参数,我用的是将主键加密*/
    }

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

    //定义表
    protected $table = "suppliers";

    protected $fillable = ['name','mobile','password'];
    //定义主键
    protected $primaryKey = "id";

}

8、配置Auth guard

修改config/auth.php
修改defaults的guards为

    'defaults' => [
        'guard' => 'api',
        'passwords' => 'supplier',
    ],

在guards中添加

 	'api' => [
    	 'driver' => 'jwt',
    	 'provider' => 'api',
  	],

在provides中,添加api

    'providers' => [
        'api' => [
            'driver' => 'eloquent',
            'model' => App\Account::class,
        ],
    ]

9、创建Accounts

<?php

namespace App\Http\Controllers\Api;

use App\Exceptions\BaseException;
use App\Account;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Translation\Tests\Dumper\JsonFileDumperTest;
use Tymon\JWTAuth\JWTAuth;
class Accounts extends Base
{
    protected $jwt;
    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

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

    /*测试方法*/
    public function test(Request $request){
        echo 'test success';
    }
}

10、将dingoh和jwt联系起来

10.1 在app\Providers\AppServiceProvider.php 中的boot方法里面添加dingo添加jwt扩展
    public function boot()
    {
        //驱动
        app('Dingo\Api\Auth\Auth')->extend('jwt', function ($app) {
            return new \Dingo\Api\Auth\Provider\JWT($app['Tymon\JWTAuth\JWTAuth']);
        });
    }
10.2 在config\api.php 找到’auth’=>[],修改
    'auth' => [
        'jwt' => 'Dingo\Api\Auth\Provider\JWT',
    ],
10.3 config\app.php中providers添加
	Dingo\Api\Provider\LaravelServiceProvider::class,
	Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
10.4 config\app.php中aliases添加
	'JWTAuth' => 'Tymon\JWTAuth\Facades\JWTAuth',
	'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
10.5 .env 中添加
	API_PREFIX=api
	API_STANDARDS_TREE=vnd
	API_VERSION=v1
	API_DEBUG=false

11、测试

登录:/api/login
laravel中使用jwt+dingo搭建api接口认证_用户认证_第1张图片
登录后:/api/test 以下几种方式验证
laravel中使用jwt+dingo搭建api接口认证_用户认证_第2张图片
laravel中使用jwt+dingo搭建api接口认证_用户认证_第3张图片
laravel中使用jwt+dingo搭建api接口认证_用户认证_第4张图片

你可能感兴趣的:(记录)