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文件: 

<?php

use App\Http\Models\Admin\Admin;

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */


    /*
        当微信小程序登录的时候,默认使用的验证规则是:api 。 
     */
    'defaults' => [
        '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 模型: 

<?php

namespace App\Models\Api;
use App\Helpers\Http;
use App\Helpers\WeChat;
use App\Http\Controllers\Helpers;
use Illuminate\Support\Facades\Auth;
use 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 = [ 
        'id',
        'open_id',
        'nickName',
        'avatarUrl',
        'real_name' ,
        'age' ,
        'gender' ,
        'phone' ,
        'province' ,
        'city' ,
        'country',
        'district' ,
        'address',
    ];
    private $token;
    protected $dates = [
        'register_at',
        'created_at',
        'updated_at'
    ];
    

    /*
        从 Post请求 中 获取到 微信的code和rawData; 
        停放一cide'‘
    */
    public function login($post){
        
        // 微信登录 获取session_key
        $session = WeChat::sessionKey($post['code']);

        if(empty($session)) return false;

        $userInfo = json_decode(htmlspecialchars_decode($post['rawData']), true);
    
        $user_id = $this->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工具类:

<?php

namespace App\Helpers;


/*

    

*/
class WeChat
{
    /**
     * 获取session_key
     * @param $code
     * @return array|mixed
     */
    public static function sessionKey($code)
    {
        /**
         * code 换取 session_key
         * ​这是一个 HTTPS 接口,开发者服务器使用登录凭证 code 获取 session_key 和 openid。
         * 其中 session_key 是对用户数据进行加密签名的密钥。为了自身应用安全,session_key 不应该在网络上传输。
         */
        // dd($code);
        $url = 'https://api.weixin.qq.com/sns/jscode2session';
        $result = json_decode(Http::curl($url, [
            'appid' => env("WX_APPID"),
            'secret' => env("WX_SECRET"),
            'grant_type' => 'authorization_code',
            'js_code' => $code
        ]), true);
        return isset($result['errcode']) ? [] : $result;
    }
}

Http工具类: 

<?php

namespace App\Helpers;


class Http
{
    /**
     * curl请求指定url (get)
     * @param $url
     * @param array $data
     * @return mixed
     */
    public static function curl($url, $data = [])
    {
        // 处理get数据
        if (!empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }
    /**
     * curl请求指定url (post)
     * @param $url
     * @param array $data
     * @return mixed
     */
    public static function curlPost($url, $data = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}

AuthController.php

<?php

namespace App\Http\Controllers\Api;

use App\Models\Api\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use stdClass;



class AuthController extends BaseController
{
    /**
     * 在构造方法中 规定 可以进入 此Controller控制器处理的请求。
     * 
     */
    public function __construct(){
        $this->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

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值