create account

Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid by duski.harahap

View this thread on: hive.blogpeakd.comecency.com
· @duski.harahap · (edited)
$22.29
Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid
#### Repository
https://github.com/bcit-ci/CodeIgniter

#### What Will I Learn?
- Decode token
- Handle response token invalid

#### Requirements
- Basic PHP
- Install Ci > 3.1
- Local server (Xampp, Wampp, or etc)
- Mysqli


#### Resources
- Code igneter - https://www.codeigniter.com/
- JSON Web tokens - https://jwt.io/

#### Difficulty
Basic

### Tutorial Content

In the previous tutorial, we have made API endpoints that we have used. You can see in the curriculum section in this tutorial. We have successfully encoded tokens and generated these tokens into an access key to access an endpoint [previous tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037). **The token** is the result of generating *user data* and *secret key* that we have created. Well in this tutorial, we will see how to *decode* the generated token, So that we know what data is contained in the token, we will learn it in this tutorial.

#### Create new endpoint to check token

In this tutorial series, we have had several API Endpoints, now we will add one new endpoint. This endpoint is useful for checking data contents from tokens sent by the user. the following is a list of the latest endpoints in **routes.php**:

**config/routes.php**

```
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

//Routes
$route['api/users']['GET'] 			= "UsersController/all_users";
$route['api/users/(:num)']['GET']	= "UsersController/detail_user/$1";
$route['api/register']['POST'] 		= "UsersController/register";
$route['api/user/(:num)']['PUT'] 	= "UsersController/update/$1";
$route['api/user/(:num)']['DELETE'] = "UsersController/delete/$1";
$route['api/login']['POST']		    = "UsersController/login";

//Endpoint to check token
$route['api/check-token']['GET'] 	= "UsersController/check_token ";

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
```

- **New endpoint:** ```$route['api/check-token']['GET'] 	= "UsersController/check_token ";```
Our new endpoint URL is in the routing ```api/check_token``` with method **GET** and the function in controller is ```check_token()```

#### Create function for ```check_token()```

We have defined the function ```check_token()``` in the routing above, now we will start to make its function in the **UserControllers.php**. So in this function later, when we want to ***decode*** the token, we put the token in the **header**. for more details, we can see the function below:

**UserControllers.php**

 ```
 public function check_token() {
		$jwt = $this->input->get_request_header('Authorization');

		try {
			//decode token with HS256 method
			$decode = JWT::decode($jwt, $this->secret, array('HS256'));
		} catch(\SignatureInvalidException $e) {

			var_dump($e); //var_dump error
		}
	}
 ```

- **Set Authorization in header :** We will decode the token, to pass the token we can put it in the **header** when doing a request to the **API**. We will pass the token with the **autorization header**. If using **POSTMAN** we can see it like the following picture:

![Screenshot_10.png](https://ipfs.busy.org/ipfs/QmbQzz6sCH55ieZyPKEsk3EuZR53Y79Y2WwLzhUW5XLvW2)


- **Get the header value :** After we set the header when requesting, we will now get the value of this value in this way:
``` $this->input->get_request_header('Authorization');```. We can use the function ```get_request_header('Authorization')``` and use the key header **'Authorization'** in this case.

- **Decode token :** We will *decode*, the opposite of *encode*. We also still use classes in the **JWT Library** that we have imported ```use  \Firebase\JWT\JWT;```. For decode token we can use like this: 

```$decode = JWT::decode($jwt, $this->secret, array('HS256'));```

to decode the token, we use function decode ```JWT::decode()``` . This function need **3 mandatory parameters**. those are:

**1.```$jwt```** is a token that we get from the header request input ```$jwt = $this->input->get_request_header('Authorization');```

**2. ```$this->secret```** is the secret key that we use when encoding data ```private $secret = "This is a secret key";```.

**3. ``` array('HS256')```** is a *hashing method* that uses when encoding data. in this tutorial, we use the **HS256 method**


#### Handling error exception with SignatureInvalidException

- **Use *try catch***

Because there is a *possibility of failed* when decoding the token, then we will use *try catch*, so we can handle the error. We can handle more specific errors by using the **JWT library** that we have *imported* in the previous [tutorial.](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111) We can import the Class like this:

**Imported:** ```use \Firebase\JWT\SignatureInvalidException;```

![Screenshot_11.png](https://ipfs.busy.org/ipfs/QmTrDyQ8L9QPtdAk8QYoQHrPrPEz4DbuGE9yuwonCuEza2)
<br>
- **Response the error**

Now we will catch and give a response when the user gives the wrong token, we can make a response like the following:
```
try {
		
		} catch(\Exception $e) {

			return $this->response([
				'success'	=> false,
				'message'	=> 'invalid token'
			]);
		}
```

The function of ```response()``` like this:
```
public function response($data) {
		$this->output
			 ->set_content_type('application/json')
			 ->set_status_header(200)
			 ->set_output(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
			 ->_display();
		exit;
	}
```
- We can set the response ```$this->response()``` when the token is invalid. We will insert wrong token and we will see The response like this:

![ezgif.com-video-to-gif (2).gif](https://ipfs.busy.org/ipfs/QmSoJRN7ECy9SAn6AroiAoxfCU6FNNZF3NoUvqrxmTsU67)
<br>

#### Result decode token


- **The result of decoding token:** After the steps above are done, now we will test whether the decode token goes well. We can check it via POSTMAN as shown below:

![ezgif.com-video-to-gif (1).gif](https://ipfs.busy.org/ipfs/QmU8RLSVFoqDDNFUL1bD9AKCXYUULhmxJLCP8kJPxbotGw)

**The first step** we have to login first to get a token you can access the endpoint login ```$route['api/login']['POST']```, we have encoded the token in the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037).

**The Second step** Now that we have the token, we can decode with the endpoint ```$route['api/check-token']['GET']``` and put the token in Headers **Authorization**. If successful you can see decoded data like this:

```
object(stdClass)#18 (4) {
  ["id"]=>
  string(1) "9"
  ["email"]=>
  string(20) "millea1234@gmail.com"
  ["iat"]=>
  int(1540902252)
  ["exp"]=>
  int(1540909452)
}
```
The data above is the data that we successfully encode when the user log in.

We can see the tokens that we get when the login has been successfully decoded and we can see the data contained in the token, now encoding and decoding is complete we can use tokens in each endpoint access in our RESTful API. I hope this tutorial can help you, thank you.


#### Curriculum

[Create RESTful API with Code Igniter #1 : Basic installation, Setup configuration and Database, Create Routes API](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182)

[Create RESTful API with Code Igniter #2 : Create API register, Models and Controllers, JSON Response](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770)

[Create RESTful API with Code Igniter #3 : Create Endpoint for Users and User detail, Dynamic functions](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409)

[Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111)

[Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037)

#### Proof of work done
https://github.com/milleaduski/RESTful-CI
πŸ‘  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authorduski.harahap
permlinkcreate-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140
categoryutopian-io
json_metadata{"app":"steemit/0.1","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmbQzz6sCH55ieZyPKEsk3EuZR53Y79Y2WwLzhUW5XLvW2","https://ipfs.busy.org/ipfs/QmTrDyQ8L9QPtdAk8QYoQHrPrPEz4DbuGE9yuwonCuEza2","https://ipfs.busy.org/ipfs/QmSoJRN7ECy9SAn6AroiAoxfCU6FNNZF3NoUvqrxmTsU67","https://ipfs.busy.org/ipfs/QmU8RLSVFoqDDNFUL1bD9AKCXYUULhmxJLCP8kJPxbotGw"],"tags":["utopian-io","tutorials","php","codeigneter"],"links":["https://github.com/bcit-ci/CodeIgniter","https://www.codeigniter.com/","https://jwt.io/","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-5-get-user-data-encode-data-and-generate-token-1540704402037","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-2-create-api-register-models-and-controllers-json-response-1539531957770","https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409","https://github.com/milleaduski/RESTful-CI"]}
created2018-10-30 13:12:09
last_update2018-10-30 13:15:45
depth0
children6
last_payout2018-11-06 13:12:09
cashout_time1969-12-31 23:59:59
total_payout_value16.748 HBD
curator_payout_value5.542 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length8,690
author_reputation60,094,717,098,672
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries
0.
accountutopian.pay
weight500
max_accepted_payout100,000.000 HBD
percent_hbd10,000
post_id74,340,002
net_rshares20,247,518,753,990
author_curate_reward""
vote details (36)
@mcfarhat ·
$7.81
Thank you for your contribution. Below is our review:
- Interesting series, although checking online, similar topics can be found with ease.
- You are decrypting using HS256. Your prior tutorial did not reflect encoding using this algo. How would that work?
- What was the driver behind using this particular algo and not something else? any added value?
- Why use a very generic exception if you know what type of exceptions to expect?
- There was a multitude of repetitions in your content description. I would advise you review your content before the final submission.
- Aside from that, nice work on the illustrations and the tutorial flow!

Your contribution has been evaluated according to [Utopian policies and guidelines](https://join.utopian.io/guidelines), as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, [click here](https://review.utopian.io/result/8/31210323).

---- 
Need help? Write a ticket on https://support.utopian.io/. 
Chat with us on [Discord](https://discord.gg/uTyJkNm). 
[[utopian-moderator]](https://join.utopian.io/)
πŸ‘  , , , , , , , , , ,
properties (23)
authormcfarhat
permlinkre-duskiharahap-create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140-20181030t164150075z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/31210323","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"}
created2018-10-30 16:41:51
last_update2018-10-30 16:41:51
depth1
children2
last_payout2018-11-06 16:41:51
cashout_time1969-12-31 23:59:59
total_payout_value5.906 HBD
curator_payout_value1.902 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,137
author_reputation150,651,671,367,256
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,352,010
net_rshares6,835,307,044,565
author_curate_reward""
vote details (11)
@duski.harahap ·
thank you @macfarhat you are right. Your advice is very subjective and constructive, you are very detailed. Your assessment will be my consideration in the next tutorial.
properties (22)
authorduski.harahap
permlinkre-mcfarhat-re-duskiharahap-create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140-20181030t174312315z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"users":["macfarhat"],"app":"steemit/0.1"}
created2018-10-30 17:43:15
last_update2018-10-30 17:43:15
depth2
children0
last_payout2018-11-06 17:43:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length170
author_reputation60,094,717,098,672
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,355,387
net_rshares0
@utopian-io ·
Thank you for your review, @mcfarhat! Keep up the good work!
properties (22)
authorutopian-io
permlinkre-re-duskiharahap-create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140-20181030t164150075z-20181103t010614z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
created2018-11-03 01:06:15
last_update2018-11-03 01:06:15
depth2
children0
last_payout2018-11-10 01:06:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length60
author_reputation152,955,367,999,756
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,574,019
net_rshares0
@steem-ua ·
#### Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
**Feel free to join our [@steem-ua Discord server](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140-20181031t034606z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
created2018-10-31 03:46:06
last_update2018-10-31 03:46:06
depth1
children0
last_payout2018-11-07 03:46:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length292
author_reputation23,214,230,978,060
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,382,619
net_rshares0
@steemitboard ·
Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@duski.harahap/posts.png?201810301915</td><td>You published more than 40 posts. Your next target is to reach 50 posts.</td></tr>
<tr><td>https://steemitimages.com/60x70/http://steemitboard.com/@duski.harahap/votes.png?201810311012</td><td>You made more than 50 upvotes. Your next target is to reach 100 upvotes.</td></tr>
</table>

<sub>_[Click here to view your Board of Honor](https://steemitboard.com/@duski.harahap)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



**Do not miss the last post from @steemitboard:**
<table><tr><td><a href="https://steemit.com/steemfest/@steemitboard/i06trehc"><img src="https://steemitimages.com/64x128/https://ipfs.io/ipfs/QmU34ZrY632FFKQ1vbrkSM27VcnsjQdtXPynfMrpxDFJcF"></a></td><td><a href="https://steemit.com/steemfest/@steemitboard/i06trehc">Be ready for the next contest!</a></td></tr><tr><td><a href="https://steemit.com/halloween/@steemitboard/trick-or-treat-publish-your-scariest-halloweeen-story-and-win-a-new-badge"><img src="https://steemitimages.com/64x128/http://i.cubeupload.com/RUyB3u.png"></a></td><td><a href="https://steemit.com/halloween/@steemitboard/trick-or-treat-publish-your-scariest-halloweeen-story-and-win-a-new-badge">Trick or Treat - Publish your scariest halloween story and win a new badge</a></td></tr><tr><td><a href="https://steemit.com/steemitboard/@steemitboard/steemitboard-notifications-improved"><img src="https://steemitimages.com/64x128/http://i.cubeupload.com/NgygYH.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/steemitboard-notifications-improved">SteemitBoard notifications improved</a></td></tr></table>

> Support [SteemitBoard's project](https://steemit.com/@steemitboard)! **[Vote for its witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1)** and **get one more award**!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-duskiharahap-20181031t143441000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2018-10-31 14:34:39
last_update2018-10-31 14:34:39
depth1
children0
last_payout2018-11-07 14:34:39
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length2,110
author_reputation38,975,615,169,260
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,412,833
net_rshares0
@utopian-io ·
Hey, @duski.harahap!

**Thanks for contributing on Utopian**.
We’re already looking forward to your next contribution!

**Get higher incentives and support Utopian.io!**
 Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via [SteemPlus](https://chrome.google.com/webstore/detail/steemplus/mjbkjgcplmaneajhcbegoffkedeankaj?hl=en) or [Steeditor](https://steeditor.app)).

**Want to chat? Join us on Discord https://discord.gg/h52nFrV.**

<a href='https://steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1'>Vote for Utopian Witness!</a>
properties (22)
authorutopian-io
permlinkre-create-restful-api-with-code-igniter-6-decode-token-and-handle-response-token-invalid-1540905123140-20181031t063733z
categoryutopian-io
json_metadata"{"app": "beem/0.20.9"}"
created2018-10-31 06:37:33
last_update2018-10-31 06:37:33
depth1
children0
last_payout2018-11-07 06:37:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length595
author_reputation152,955,367,999,756
root_title"Create RESTful API with Code Igniter #6 : Decode token and Handle response token invalid"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id74,389,203
net_rshares0