token based authentication in php

前端 未结 3 967
误落风尘
误落风尘 2021-02-14 06:17

I have an REST service on my webserver, written in php. I was wondering, what would be the best authentication (besides basic http access authentication). I\'ve heared of token-

3条回答
  •  遇见更好的自我
    2021-02-14 06:50

    You can use fire-base php JWT (JSON Web Token) for token based authentication.

    1)Install php jwt by running composer command composer require firebase/php-jwt

       require_once('vendor/autoload.php');
       use \Firebase\JWT\JWT; 
       define('SECRET_KEY','Your-Secret-Key')  // secret key can be a random string  and keep in secret from anyone
       define('ALGORITHM','HS512')
    

    After that Generate your token

    $tokenId    = base64_encode(mcrypt_create_iv(32));
                    $issuedAt   = time();
                    $notBefore  = $issuedAt + 10;  //Adding 10 seconds
                    $expire     = $notBefore + 7200; // Adding 60 seconds
                    $serverName = 'http://localhost/php-json/'; /// set your domain name 
    
    
                    /*
                     * Create the token as an array
                     */
                    $data = [
                        'iat'  => $issuedAt,         // Issued at: time when the token was generated
                        'jti'  => $tokenId,          // Json Token Id: an unique identifier for the token
                        'iss'  => $serverName,       // Issuer
                        'nbf'  => $notBefore,        // Not before
                        'exp'  => $expire,           // Expire
                        'data' => [                  // Data related to the logged user you can set your required data
                    'id'   => "set your current logged user-id", // id from the users table
                     'name' => "logged user name", //  name
                                  ]
                    ];
                  $secretKey = base64_decode(SECRET_KEY);
                  /// Here we will transform this array into JWT:
                  $jwt = JWT::encode(
                            $data, //Data to be encoded in the JWT
                            $secretKey, // The signing key
                             ALGORITHM 
                           ); 
                 $unencodedArray = ['jwt' => $jwt];
    

    provide this token to your user "$jwt" . On each request user need to send token value with each request to validate user.

     try {
               $secretKey = base64_decode(SECRET_KEY); 
               $DecodedDataArray = JWT::decode($_REQUEST['tokVal'], $secretKey, array(ALGORITHM));
    
               echo  "{'status' : 'success' ,'data':".json_encode($DecodedDataArray)." }";die();
    
               } catch (Exception $e) {
                echo "{'status' : 'fail' ,'msg':'Unauthorized'}";die();
               }
    

    You can get step by step full configurations for php token based authentication

提交回复
热议问题