laravel整合jwt使用

参考:https://segmentfault.com/a/1190000012606246(主要)
https://www.cnblogs.com/agang-php/p/10480575.html
https://learnku.com/laravel/t/21265(报错)

今天自己尝试配置jwt,其实jwt我之前也有研究过具体看我这篇博文其实这个就是个帮你封装好的使用token的插件,俗称jwt

  1. 首先composer安装jwtcomposer require tymon/jwt-auth 1.0.0-rc.1 (可以把后面版本号去掉)

  2. 在config/app.php 文件的providers数组加入如下(扩展功能到你的应用程序)

    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

  3. 在config生成配置文件jwt.php,执行命令php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

  4. 生成密钥php artisan jwt:secret

  5. 修改框架的登录验证方式,在config/auth.php 将guard-api-driver改为jwt,如下’guards’ => [
    ‘api’ => [
    ‘driver’ => ‘jwt’,
    ‘provider’ => ‘users’,
    ], ],

    ‘providers’ => [
    ‘users’ => [
    ‘driver’ => ‘eloquent’,
    ‘model’ => \App\Modules\User\Models\User::class,
    ],
    ],

  6. 新建User模型,这个就是我来操作我的users表的model

    <?php namespace App\Modules\User\Models; 
    Tymon\JWTAuth\Contracts\JWTSubject; use
    Illuminate\Notifications\Notifiable; use
    Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable implements JWTSubject {
        use Notifiable;
    
        protected $fillable = ['username', 'password', 'phone', 'open_id', 'avatar', 'register_ip', 'city'];
    
        public function getJWTIdentifier()
        {
            //  Implement getJWTIdentifier() method.
            return $this->getKey();
        }
    
        public function getJWTCustomClaims()
        {
            // Implement getJWTCustomClaims() method.
            return [];
        } } ```
    
  7. 再写个中间件用来检测请求是否带着token,验证下

    <?php namespace App\Http\Middleware; 
    
    use
    Illuminate\Support\Facades\Auth; use Closure; 
    useTymon\JWTAuth\Exceptions\JWTException; use
    Tymon\JWTAuth\Http\Middleware\BaseMiddleware; use
    Tymon\JWTAuth\Exceptions\TokenExpiredException; use
    Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
    
    class RefreshToken extends BaseMiddleware {
        public function handle($request, Closure $next)
        {
            // 检查此次请求中是否带有 token,如果没有则抛出异常
            $this->checkForToken($request);
            try{
                // 检测用户的登录状态,如果正常则通过
                if($this->auth->parseToken()->authenticate()){
    
                    return $next($request);
                }
                throw new UnauthorizedHttpException('jwt-auth', '未登录');
            }catch (TokenExpiredException $exception){
                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());
                }
    
                // 在响应头中返回新的token
                return $this->setAuthenticationHeader($next($request), $token);
            }
        } }
    
    
  8. 把刚刚新建的中间件加入到可被路径调用的,在App/Http/Kernel.php的$routeMiddleware数组加入'refresh.token' => RefreshToken::class,
    api.php路径文件这样调用

Route::group(['prefix' => 'admin/auth', 'middleware' => ['refresh.token'] ], function () {

    Route::any('test', ['uses' => 'Admin\AuthController@test']); // 测试

});
  1. 新建个用户register

    $params = [
                'username' => '小明',
                'password' => bcrypt('123456')
            ];
            $user = User::create($params); ```
    
  2. 登录验证返回token

    php $token = Auth::guard('api')->attempt($params);

  3. postman测试,如下图
    在这里插入图片描述

posted @ 2021-01-22 17:15  蜗牛使劲冲  阅读(5)  评论(0编辑  收藏  举报  来源