api identity verification of the token

Before and after the end of the separation or to support multiple web applications, then the original session on the use of cookies or there will be a big problem
so we used the token

Use

1. pass the front landing account password information [like] a verification code to the backend

2. The back-end authentication log-in information, generate a unique identity token is bound to the user, and returned to the front

3. The front end of the token stored in the buffer, each request, in a header or a URL token transmitted to the rear end

4. The front end of the rear end of the token transmitted from token for comparison, verify the expiration time and the result is returned to the rear end

 

Database Design:

 

 

 

 

php code:

    // test whether the landing 
    public  function cehckLogin () {
         IF ( empty ( $ the this -> headers [ 'token' ])) { 
            AException ( 'token verification fails', 401 ); 
        } 
        $ User = Model ( 'the User') -> WHERE ([ 'token' => $ the this -> headers [ 'token']]) -> Find (); 

        IF (! $ User ) { 
            AException ( 'token verification fails', 401 ); 
        } 
        IF ( User $ -> token_timeout < Time ()) { 
            AException ( 'token expires',401401);
        }
        // token续期
        $code_out = time() + 60*60*24* config('IAuth.token_time');
        model('User')->where(['token' => $this->headers['token']])->update(['token_timeout' => $code_out]);
        return $user->id;
    }


    // 设置唯一的token
    public static function setAppLoginToken($userid = ''){
        $str = md5(uniqid(md5(microtime((true)),true)));
        $str = sha1($str.$userid);
        return $str;
    }

 

    // 更新token
    public function updateToken($id, &$token, &$token_timeout){
        $token = 0;
        $token_timeout = 0;

        $code = IAuth::setAppLoginToken($id);
        $code_out = time() + 60*60*24* config('IAuth.token_time');
        $res = $this->where(['id' => $id])->update(
            ['token' => $code, 'token_timeout' => $code_out]
        );
        if($res){
            $token = $code;
            $token_timeout = $code_out;
        }
    }

 

Guess you like

Origin www.cnblogs.com/cl94/p/12507961.html