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. 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 routingapi/check_token
with method GET and the function in controller ischeck_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:
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 functionget_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. We can import the Class like this:
Imported: use \Firebase\JWT\SignatureInvalidException;
- 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:
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:
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.
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) "[email protected]"
["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 #2 : Create API register, Models and Controllers, JSON Response
Create RESTful API with Code Igniter #5 : Get user data, Encode data, and Generate token
Thank you for your contribution. Below is our review:
Your contribution has been evaluated according to Utopian policies and 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.
Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]
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.
Thank you for your review, @mcfarhat! Keep up the good work!
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
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 or Steeditor).
Want to chat? Join us on Discord https://discord.gg/h52nFrV.
Vote for Utopian Witness!
Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :
Click here to view your Board of Honor
If you no longer want to receive notifications, reply to this comment with the word
STOP
Do not miss the last post from @steemitboard: