ThinkPHP5 conversation verified using jwt

Prior to the past, there is no separation of the front and rear ends of the project done, are rendered server template, and then the account with cookie and session management authority to verify or login status. Later, after contact with vue and applets, front and rear end during the separation and you will experience permission authentication and logon session save. Because the HTTP protocol is open, you can call fancy. So, if the interface does not want to be free to call, you need to do access control, user authentication is good, it is allowed to call API.

JWT advantage

1: The server does not need to preserve traditional session information, there is no cross-domain transmission problems, reduce server overhead.

2: jwt a simple structure, occupy a few bytes, to facilitate transport.

3: json format general, you can use different languages.

jwt consists of three parts:

Header (header) payload (payload) and definition information contains custom information visa (Signature)

So here will be used to access the token bearer, is jwt; Definition: In order to verify the user's identity, requires the client to provide a reliable authentication information to the server, called Token, this token is usually composed of Json data format, by generating a string hash hash algorithm, so called Json Web token (Json representation of the original value of the token is a data format Json, web representation is spread on the Internet, a token representing token, referred JWT)

First we used at the GitHub composer require firebase/php-jwtdownload firebase / php-jwt, how a composer I is not tired, my past articles inside installation tutorial.

After installed, we can create a new user control to test the integrity of the code, we first create three control methods

Base.php

Base.php basis controller is mainly used to verify each time to accept the request, verify whether the http request header which carry a token, how to put the request token inside the head, this will do the front-end.

<?php
/**
 * Created by PhpStorm.
 * User: nobita
 * Date: 2/15
 * Time: 14:55
 */

namespace app\user\controller;

use think\Request;
use Firebase\JWT\JWT;

use think\Controller;

class Base extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        $this->checkToken();
    }

    public function checkToken()
    {
        $header = Request::instance()->header();
        if ($header['authorization'] == 'null'){
            echo json_encode([
                'status' => 1002,
                'msg' => 'Token不存在,拒绝访问'
            ]);
            exit;
        }else{
            $checkJwtToken = $this->verifyJwt($header['authorization']);
            if ($checkJwtToken['status'] == 1001) {
                return true;
            }
        }
    }

    //校验jwt权限API
    protected function verifyJwt($jwt)
    {
        $key = md5('nobita');
        // JWT::$leeway = 3;
        try {
            $jwtAuth = json_encode(JWT::decode($jwt, $key, array('HS256')));
            $authInfo = json_decode($jwtAuth, true);
            $msg = [];
            (! empty ($ authInfo [ 'user_id'])) IF { 
                $msg = [
                    'Status' => 1001, 
                    ' MSG '=>' the Token verified ' 
                ]; 
            } the else { 
                $ MSG = [ 
                    ' Status' => 1002, 
                    'MSG '=>' Token authentication fails, the user does not exist ' 
                ]; 
            } 
            return $ MSG; 
        } the catch (\ Firebase \ the JWT \ SignatureInvalidException $ E) { 
            echo json_encode ([ 
                ' Status '=> 1002, 
                ' MSG '=>' Token invalid ' 
            ]); 
            Exit;
        } catch (\Firebase\JWT\ExpiredException $e) { 
            echo json_encode ([ 
                'Status' => 1003,
                'msg' => 'Token expires'
            ]);
            exit;
        } catch (Exception $e) {
            return $e;
        }
    }
}

Login.php

Log controller, is used to verify the user as long as the entered password matches the account information in the database, if it matches, on the application token, and returns the token to the distal stored locally, each time a request to the token if the request header inside

<?php
/**
 * Created by PhpStorm.
 * User: nobita
 * Date: 2/15
 * Time: 14:55
 */

namespace app\user\controller;

use app\common\model\nobita\Test as TestModel;

use Firebase\JWT\JWT;

class Login
{
    public function index()
    {
        $data = input('post.');
        $username = htmlspecialchars($data['username']);
        $password = htmlspecialchars($data['password']);
        $user = TestModel::where('username', $username)->find();
        if (!empty($user)) {
            if ($username === $user['username'] && $password === $user['password']) {
                $msg = [
                    'Status' => 1001, 
                    'MSG' => 'login success', 
                    'JWT' => Self :: createJwt ($ User [ 'ID']) 
                ]; 
                return $ MSG; 
            } the else { 
                return [ 
                    'Status' = > 1002, 
                    'MSG' => 'wrong account password' 
                ]; 
            } 
        } the else { 
            return [ 
                'Status' => 1002, 
                'MSG' => 'Please enter the account password' 
            ];
        } 
    } 

    Public function createJwt ($ the userId) 
    { 
        $ Key = MD5 ( 'nobita'); // JWT issued key, authentication token when the need to use
        $ time = time (); // Issue time 
        $ expire = $ time + 14400; // expiration time 
        $ token = Array ( 
            "user_id" => $ userId, 
            "ISS" => "https://199508.com" // issuing organization 
            "aud" => "https://199508.com" , // issuance of 
            "IAT" => $ Time, 
            "NBF" => $ Time, 
            "exp" => $ The expire 
        ); 
        $ :: = encode the JWT JWT (token $, $ Key); 
        return $ JWT; 
    } 
}

User.php

Used to verify the integrity of the code

<?php
/**
 * Created by PhpStorm.
 * User: nobita
 * Date: 2/15
 * Time: 15:24
 */

namespace app\user\controller;

use think\Request;

use app\common\model\nobita\Test as TestModel;

class User extends Base //继承基础控制器
{
    public function index()
    {
        return TestModel::all();
    }
}

 

Guess you like

Origin www.cnblogs.com/yehuisir/p/11521233.html