JWT(laravel5.5版本)

1.JWT文档地址
2.多表认证(比如你前后台都需要做token,并且模型不一样时)参考地址
3.大神参考地址
说明我的admin结构

public function up()
    {
        Schema::create('admin', function (Blueprint $table) {
            $table->increments('admin_id');
            $table->string('admin_name', 30)->comment('管理员名称');
            $table->string('password', 32)->comment('密码');
            $table->string('avatar', 200)->comment('头像');
            $table->integer('state');
            $table->timestamps();
        });
    }

4.laravel引入jwt插件

composer require tymon/jwt-auth 1.0.*

5.在 config/app.php 中provider中添加

Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
JWT(laravel5.5版本)_第1张图片
image.png

6在 config/app.php 中aliases中添加

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,

7.修改config/auth.php

JWT(laravel5.5版本)_第2张图片
image.png

JWT(laravel5.5版本)_第3张图片
指定guard

JWT(laravel5.5版本)_第4张图片
指定默认模型

8.修改模型(模型很重要)

getKey();
    }

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

    }
    public function getAuthPassword()
    {

    }
    public function getRemenberToken()
    {

    }
    public function setRememberToken($value)
    {

    }
    public function getRememberTokenName()
    {

    }
}

9使用示例

备注:我的authService

class AuthService 
{
    /**
     * 获取admin信息
     *
     * @param string $login_name 用户名
     * @param string $password 密码
     * 
     **/
    public function get_admin_info($login_name, $password)
    {
        try {
            return Admin::where([
                'login_name' => $login_name,
                'password' => md5($password)
            ])->select('admin_id', 'admin_name', 'login_name', 'avatar', 'state')->first();
        } catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }
}

9.1生成token

 #登录
    public function authLogin(Request $request)
    {
        $params = $request->params;
        // dd($params);
        try {
            $admin_data = $this->authService->get_admin_info($params['username'], $params['password']);
            #生成token
            $token = $this->auth->fromUser($admin_data);
            // dd($token);
            return Responser::success([
                'token' => $token,
                'expires_in' => $this->auth->factory()->getTTL() * 60,
                'userinfo' => $admin_data->toArray()
            ]); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }

9.2刷新token

#刷新令牌,使当前无效
    public function refresh_token(Request $request) 
    {
        $params = $request->params;
        try {
            $token = $this->auth->getToken()->get();//验证是否能获取到token
            $newToken = auth()->refresh();
            return Responser::success([
                'newtoken' => $newToken,
                'expires_in' => $this->auth->factory()->getTTL() * 60
            ]); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }

9.3删除token

public function login_out(Request $request)
    {
        try {
            $token = $this->auth->getToken()->get();
            $result = $this->auth->invalidate(); 
            return Responser::success(); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }

9.4验证token(中间键里面)

public function handle($request, Closure $next)
    {
        // # 过滤内网
        // $ip = $request->getClientIp();
        // # 获取IP白名单
        // $white_list = explode(',', env('WHITE_HOST'));
        // if (!in_array($ip, $white_list)) {
        //     return Responser::error(403);
        // }
        try {
            $token = $this->auth->setRequest($request)->getToken();
            // dd($token);
            // $user = $this->auth->parseToken()->authenticate();
            $user = $this->auth->toUser($token);
            dd($user);
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            return Responser::error(402);
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            try {
                $token = $this->auth->getToken()->get();//验证是否能获取到token
                $newToken = auth()->refresh();
            } catch (\Exception $e) {
                return Responser::error($e->getMessage());
            }
            #刷新token并且返回新token
            return Responser::error(406,[
                'newToken' => $newToken
            ]);
        } catch (JWTException $e) {
            return Responser::error(402);
        }
            
        dd('66');
        return $next($request);
    }

最后再贴一张我的controller

auth = $auth;
        $this->authService = new AuthService;
        // $this->admin = $admin;
    }
    #登录
    public function authLogin(Request $request)
    {
        $params = $request->params;
    
        try {
            $admin_data = $this->authService->get_admin_info($params['username'], $params['password']);
            #生成token
            $token = $this->auth->fromUser($admin_data);
            // dd($token);
            #启动监听器
            event(new LoginEvent($admin_data, new Agent(), \Request::getClientIp(), time()));
            return Responser::success([
                'token' => $token,
                'expires_in' => $this->auth->factory()->getTTL() * 60,
                'userinfo' => $admin_data->toArray()
            ]); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }

    #刷新令牌,使当前无效
    public function refresh_token(Request $request) 
    {
        $params = $request->params;
        try {
            $token = $this->auth->getToken()->get();//验证是否能获取到token
            $newToken = auth()->refresh();
            return Responser::success([
                'newtoken' => $newToken,
                'expires_in' => $this->auth->factory()->getTTL() * 60
            ]); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }
    /**
     * 退出登录
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function login_out(Request $request)
    {
        try {
            $token = $this->auth->getToken()->get();
            $result = $this->auth->invalidate(); 
            return Responser::success(); 
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }
}

你可能感兴趣的:(JWT(laravel5.5版本))