美文网首页
JWT(laravel5.5版本)

JWT(laravel5.5版本)

作者: 杨森Janssen | 来源:发表于2018-02-26 10:00 被阅读2442次

    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,
    
    image.png

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

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

    7.修改config/auth.php

    image.png
    指定guard
    指定默认模型

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

    <?php
    
    namespace App\Models;
    
    use Tymon\JWTAuth\Contracts\JWTSubject;
    
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class Admin extends Authenticatable implements JWTSubject
    {
        use Notifiable;
        protected $table = 'admin';
        protected $primaryKey = 'admin_id';
        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $fillable = ['adminname', 'login_name', 'password', 'avatar', 'state'];
        protected $hidden = [
            'password',
        ];
    
        /**
         * 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 [];
        }
        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

    <?php
    namespace App\Http\Controllers\Admin\Auth;
    
    use App\Http\Controllers\Controller;
    use Illuminate\Http\Request;
    
    use Tymon\JWTAuth\JWTAuth;
    use Tymon\JWTAuth\Exceptions\JWTException;
    use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
    
    use App\Utils\Responser;
    use App\Services\AuthService;
    
    use App\Events\LoginEvent; 
    use Jenssegers\Agent\Agent; 
    
    class AuthController extends Controller
    {
    
        protected $auth, $authService;
        protected $admin;
        public function __construct(JWTAuth $auth)
        {
            $this->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版本)

          本文链接:https://www.haomeiwen.com/subject/lbqqxftx.html