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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章