Press "Enter" to skip to content

How to use JWT in CodeIgniter for creating API Authorization token

0

In this tutorial, we are going to learn, how to use JWT in Codeigniter for creating API Authorization token. We will use a JWT Class in CodeIgniter for encoding and decoding. Purpose of Authorization token is to an authorized API call to secure access. 

JWT:- JSON Web Token proposed in December 2010 for HTTP Authorization headers or query string parameters, data has to be transmitted in JSON and has a payload of JSON Web Signature, JWT data represented using Base64 URL encoding.

JWS:- JSON Web Signature is a cryptographic mechanism designed to secure data.

Before starting we need JWT class and put into a helper directory of a CodeIgniter and follow things below:-

Now load this class in Controller:- First, we will create an Authorization token

     Class UserAuthorization extends CI_Controller{
           function create_token(){
                $this->load->helper('jwt');
                $jwt = new JWT();
                $payload = array(
                    'id' => '123',
                    'email' => '[email protected]',
                    'time' => time()
                );
                $token = $jwt->encode($payload, key);//key is a constant defined once
                return_api(true, Atuhorization token,$token);
           }
     }

Now, we are going to authorize the token

     Class UserAuthorization extends CI_Controller{
          function authorize(){
               $thid->load->helper('jwt');
               $headers = $ci->input->request_headers();
	       if(!isset($headers['Authorization'])){
			return_api(false, 'Please Send Authorization token!');
	        }
                $token = $headers['Authorization'];
                $jwt = new JWT();
		try{
			$payload = $jwt->decode($token, key);//$payload is your metadata send by you & key is the contant value ones defined by you.
			if($tok === $token){//$tok is your saved token in databse
				// return_api(true, 'Access Authorize');   			
			}else{
				return_api(true, 'UnAuthorize Access Token missmatch!', 401);
			}			
		}catch(Exception $e){
			return_api(true, 'UnAuthorize Access!', 401);
		}  
           }
}

Happy Coding! If you have any doubts about this tutorial you can comment or directly contact me. 

Some of the useful tutorial you may like for CodeIgniter:-

How to upload excel file in CodeIgniter

Employee Management System Php Projects

How to send Emails using Sendgrid in PHP?
How to upload excel and CSV file in CodeIgniter framework to MySQL