Laravel框架 配置 【JWT】 自动验证 放在【请求头】中的 【 token】

微信小程序开发

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

"tymon/jwt-auth": "^1.0.0-rc.1"

2. 运行以下命令,更新依赖:

composer update

3. 运行以下命令, 生成jwt.php配置文件: 

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

4. 修改config\auth.php文件: 

 [
        'guard' => 'api',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */


    /*
        配置验证规则: 
                api 验证规则采用的 : 
                            【验证驱动】 是  JWT
                            【验证代理对象】 是 users

     */
    'guards' => [

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

        'admin' => [
            'driver' => 'jwt',
            'provider' => 'admins',
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */


    /*
        users 与 数据库表中数据 对比的 规则: 
                users 模型 与 数据库表对比时 采用的 驱动 为  Eloquent 。 
                数据库表 映射 的 Model模型为:   App\Models\Api\User::class  
     */
    'providers' => [

        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\Api\User::class,
        ],

        'admins' => [
            'driver' => 'eloquent',
            'model' => App\Models\Api\Admin\Admin::class,
        ],

    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
        ],
    ],

];

3、继续按照: JWT官方配置文档

4. 获取当前用户的对象实例: $user = auth('api')->user();

5. 生成JWT密钥: 

php artisan jwt:secret

以上都配置完成后,可以直接粘贴以下代码:

User 模型: 

register($session['openid'], $userInfo);
        $this->token = auth("api")->tokenById($user_id);
       
        return $user_id;
    }
    
      /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $referee_id
     * @return mixed
     */
    private function register($open_id, $data, $referee_id = null)
    {
        $data['nickName'] = preg_replace('/[\xf0-\xf7].{3}/', '', $data['nickName']);
        $model = self::updateOrCreate(['open_id' => $open_id],$data); 
        return $model['id'];
    }


    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }
   

     /**
     * 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 [];
    }
  
}

WeChat工具类:

 env("WX_APPID"),
            'secret' => env("WX_SECRET"),
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ]), true);
        return isset($result['errcode']) ? [] : $result;
    }
}

Http工具类: 

AuthController.php

middleware('auth:api', ['except' => ['login']]);
    }


    /**
        这是一个Post请求: 
                    请求体的 body中 有 Code 和 rawData 两个字段。返回给前端token和user_id。
     
    */
    public function login(Request $request){
       
        $model = new User;
        $user_id = $model->login($request->post());
    
        if($user_id){
            return $this->success([
                'id' => $user_id,
                'token' => $model->getToken()
            ],"登录成功");
        }
        return $this->error("code已使用");
    }


    /*
        返回一个 验证信息 对象 auth('api')
    */
    public function guard(){
        return auth("api");
    }
}

——————————我的微信小程序开发【JWT自动验证token】的laravel项目模板:

     git clone  https://git.dev.tencent.com/AmeirYang/After_Home_School_Coming.git

 

你可能感兴趣的:(Laravel框架)