#### Repository https://github.com/bcit-ci/CodeIgniter #### What Will I Learn? - Learning the **JWT (JSON Web Token)** concept - Create login function - Decode password #### 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 This tutorial we will learn something different from the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409), in this application we use the API so our login system will use tokens, unlike ordinary login applications that only use Session, so we need to use additional tools, to make the system login using tokens. We will add the system token on user authentication on our application. We will use [JSON Web tokens](https://jwt.io/). ### JSON Web tokens - ***What is JSON web tokens?*** to help you explain what JSON web tokens are, you can see on their official website https://jwt.io . So the point is after I use this tool, **Json web token** is a password or token that is given to validate that if the user is valid. So the token is saved by the user and when there is an action that requires access to tokens. the user will give the token so that the system can recognize that the one to be given access is a valid user. the following is the description:  The structure have three things as we see in the picture above as follows: **1. Header** ``` { "alg": "HS256", "typ": "JWT" } ``` in the header it will only consist of the algorithm used ```"alg": "HS256"``` and the type is jwt ``` "typ": "JWT"```. **2. Payload** ``` { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 } ``` **Payload** is the data that we will pass to the user, we can put the data requested by the user. **3. Verify Signature** ``` HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret ) ; ``` **Verify Signature** is the result of the hash of the **header** ```base64UrlEncode(header)``` and **payload** ```base64UrlEncode(payload)```. then combined by secret keywords ```your-256-bit-secret```, this keyword is confidential only the server knows. Well when we login we will get an example of a token like this ``` eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c ``` The explanation above is a concept from JWT. to connect when all data and hashing it. We need additional tools namely https://github.com/firebase/php-jwt <br> ### Use Firebase Jwt - **Extends the code** to use this library we can see the code and copy the file in the src folder https://github.com/firebase/php-jwt/tree/master/src.  After you copy you can put it in our application in the **application/libararies** folder.  <br> - **Include the code in our app** We have extracted the code in the library, then we will use it in our code. here is the way to include the code: **UsersController.php** ``` <?php defined('BASEPATH') OR exit('No direct script access allowed'); require_once APPPATH .'/libraries/JWT.php'; // Include the JWT.php use \Firebase\JWT\JWT; //namespace in jwt class UsersController extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('user'); } 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; } public function register() { return $this->response($this->user->save()); } public function all_users() { return $this->response($this->user->get_all()); } public function detail_user($id) { return $this->response($this->user->get_all($id)); } } ``` - We will use the JWT.php file so we can include the file in our code like this ```require_once APPPATH .'libraries/JWT.php';``` - ```JWT.php``` file has a namespace ```namespace Firebase\JWT;```. So we can use it as follows ```use \Firebase\JWT\JWT;``` **JWT** is the name of class in **JWT.php**. ### Use tokens in the login system We have understood the token authentification. now we will implement it in our authentication system, in the previous [tutorial](https://steemit.com/utopian-io/@duski.harahap/create-restful-api-with-code-igneter-1-basic-installation-setup-configuration-and-database-create-routes-api-1539354852182) we have made the routing for the **login**. ``` $route['api/login'] = "UsersController/login"; ``` If we look at the routing above, routing ```$route['api/login']``` uses the login function ```UsersController/login``` found in **UsersController**. then we will create a login function on **UsersController.php**. <br> - **Checking valid login** The first step that will be done is to check whether the user who is currently logged in is a valid user, we can make the function as follows: ``` public function login() { if (!$this->user->is_valid()) { return $this->response([ 'success' => false, 'message' => 'Password or Email is wrong' ]); } } ``` - We make the ```function login ()``` to match what we use in the login routing and then we will create a function that is in the model that is useful for checking whether the user is valid. The function name is ```$this->user->is_valid()```. - So later the ```$this->user->is_valid() ``` will return the ***boolean*** value, then we can check the ***boolean*** value, If the result is **false**. that's means , the email and password is wrong and we can send a response like this: ``` return $this->response([ 'success' => false, 'message' => 'Password or Email is wrong' ]); ``` <br> - **Make function ```is_valid()``` in model.php** Now we will create thefunction ```is_valid ()``` in the **User.php** model, This function will determine whether the user is a valid user, so what we will do is matching the email and password input by user. The following is the code that we will use. **User.php** ``` public function get_all($key = null, $value = null) { if($id != null) { $query = $this->db->get_where('users', array($key => $value)); return $query->result(); } $query = $this->db->get('users'); return $query->result(); } public function is_valid() { $email = $this->input->post('email'); $password = $this->input->post('password'); $hash = $this->get_all('email', $email)[0]->password; if(password_verify($password, $hash)) return true; return false; } ``` - Because we use the post method on the route API we can take user input values like this: ``` $email = $this->input->post('email'); $password = $this->input->post('password'); ```  ```$this->input->post('email')```: **'email'** is the key that is posted on the body. ```$this->input->post('password')```: **'password'** is the key that is posted on the body. - After we get the input value, we can check whether the email entered by the user is a valid email. Therefore we can use the function that we have made in the previous tutorial, the function ```get_all ()```. We can use it by passing the ```$email``` parameters we get from ```$this->input->post('email');```. We just want to retrieve password data we can do it as follows ```$this->get_all('email', $email)[0]->password``` - Now we have got the value of the password that we can save in the ```$hash``` variable, but the password that we can still in the results of hashing that we do when registered.  - We have got a password that has been hashed, now we will do ```password_verify()``` to check whether the hashed password is a valid password from the user. ```password_verify($password, $hash)``` has two mandatory parameters, namely **the original password** ```$password``` and **the password that has been hashed** ``` $hash```. The result of this function is ***true*** or ***false***. - Then we will check whether the result of the password_verify function is *correct*, If it's correct then ***return true*** if the wrong ***return false***. <br> We will check whether the code that we write goes well, I will do ```die('User is valid');``` to give the response if the **email and password** are correct. ``` public function login() { if (!$this->user->is_valid()) { return $this->response([ 'success' => false, 'message' => 'Password or Email is wrong' ]); } die('User is valid'); } ```  We can see in the picture above us when the ***password is wrong*** we will get a response: ``` { "success": false, "message": "Password or Email is wrong" } ``` We have succeeded in creating a login system in our authentication system, we also understand the basic concepts of the Json web token, in the next tutorial we will start using tokens as validations for every request we make, you can explore the use of tokens in the deeper RESTful API again, hopefully this tutorial will 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) #### Proof of workdone https://github.com/milleaduski/RESTful-CI
author | duski.harahap | ||||||
---|---|---|---|---|---|---|---|
permlink | create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111 | ||||||
category | utopian-io | ||||||
json_metadata | {"app":"steeditor/0.1.2","format":"markdown","image":["https://ipfs.busy.org/ipfs/QmU5NpyA4aHuDuz3kqEm4JAGk8My2apxFbKJFFHhcqCeHS","https://ipfs.busy.org/ipfs/QmYpUfqeSbC9nQAABBW6hxByx2mN6tf6frcSTem3iFqXbf","https://ipfs.busy.org/ipfs/QmRa4nKr3ia1o9WhXHM7mDZKjT84cv86ayNbZGCqNShxS3","https://ipfs.busy.org/ipfs/QmS7oUAYt49u3M685ZJfG28jRMQCqLcBDmDio9yGagN9BR","https://ipfs.busy.org/ipfs/QmVyKtge9hZ5wNZ9Yr4AXFMzj9BJzSvZUE32vDxP6pWTyX","https://ipfs.busy.org/ipfs/QmQDkT3iMfzPnahD9iaV6WtDLDKQMLokb8SHRZrsMW6Eac","https://ipfs.busy.org/ipfs/QmNwggLM6KYAmFnL84DTPCBwd3hdEiKuCFqnDL3GYopWNN"],"tags":["utopian-io","tutorials","php","codeigneter"],"users":["duski"],"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-igneter-3-create-endpoint-for-user-dan-user-detail-dynamic-functions-1539784449409","https://jwt.io","https://github.com/firebase/php-jwt","https://github.com/firebase/php-jwt/tree/master/src.","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://github.com/milleaduski/RESTful-CI"]} | ||||||
created | 2018-10-24 15:44:21 | ||||||
last_update | 2018-10-24 15:44:21 | ||||||
depth | 0 | ||||||
children | 5 | ||||||
last_payout | 2018-10-31 15:44:21 | ||||||
cashout_time | 1969-12-31 23:59:59 | ||||||
total_payout_value | 34.119 HBD | ||||||
curator_payout_value | 11.650 HBD | ||||||
pending_payout_value | 0.000 HBD | ||||||
promoted | 0.000 HBD | ||||||
body_length | 10,666 | ||||||
author_reputation | 60,094,717,098,672 | ||||||
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" | ||||||
beneficiaries |
| ||||||
max_accepted_payout | 100,000.000 HBD | ||||||
percent_hbd | 10,000 | ||||||
post_id | 73,968,470 | ||||||
net_rshares | 41,634,726,907,299 | ||||||
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
miniature-tiger | 0 | 79,184,977,854 | 50% | ||
dune69 | 0 | 244,293,241 | 0.5% | ||
aleister | 0 | 4,492,111,553 | 30% | ||
catchawhale | 0 | 3,964,551,834 | 1% | ||
bachuslib | 0 | 20,362,068,496 | 100% | ||
fbslo | 0 | 57,672,171,299 | 20% | ||
caladan | 0 | 103,979,442 | 0.5% | ||
utopian-io | 0 | 40,412,584,047,136 | 27.88% | ||
jaff8 | 0 | 72,375,432,465 | 100% | ||
gattino | 0 | 561,318,522 | 5% | ||
mvanyi | 0 | 1,567,018,192 | 100% | ||
amosbastian | 0 | 93,674,526,449 | 43.72% | ||
jesusjacr | 0 | 401,255,040 | 0.34% | ||
indianteam | 0 | 454,268,849 | 43.72% | ||
portugalcoin | 0 | 6,452,507,054 | 30% | ||
sudefteri | 0 | 2,697,733,875 | 100% | ||
bringolo | 0 | 34,333,242,577 | 99.71% | ||
aderemi01 | 0 | 581,632,838 | 100% | ||
sttest1 | 0 | 0 | 4.59% | ||
sttest2 | 0 | 0 | 29.9% | ||
properfraction | 0 | 676,300,222 | 100% | ||
simplymike | 0 | 82,395,228,976 | 70% | ||
kabil | 0 | 6,057,651,739 | 100% | ||
coinsandchains | 0 | 3,734,972,848 | 8.15% | ||
moreone | 0 | 494,035,290 | 100% | ||
dima.nurgaliev | 0 | 493,974,348 | 100% | ||
lilihaovhan | 0 | 494,519,632 | 100% | ||
minasyanvahe | 0 | 493,906,959 | 100% | ||
timedouble | 0 | 493,801,586 | 100% | ||
molly.smith | 0 | 493,865,314 | 100% | ||
mightypanda | 0 | 124,121,067,988 | 100% | ||
sergeyvoronov | 0 | 493,508,467 | 100% | ||
trekkingglucose | 0 | 494,549,686 | 100% | ||
suburbanmammary | 0 | 494,625,001 | 100% | ||
noxiouspick | 0 | 494,479,366 | 100% | ||
pooruthenium | 0 | 494,572,240 | 100% | ||
strangetwelve | 0 | 494,528,140 | 100% | ||
wailibis | 0 | 494,099,667 | 100% | ||
gutalveoli | 0 | 494,618,166 | 100% | ||
brandcomment | 0 | 494,949,015 | 100% | ||
knifedutiful | 0 | 494,571,553 | 100% | ||
stimulusmaybe | 0 | 494,383,606 | 100% | ||
spotted | 0 | 24,377,724,339 | 50% | ||
minnowsmith | 0 | 413,127,162 | 25% | ||
ayisigi | 0 | 535,120,453 | 100% | ||
almostegret | 0 | 495,309,003 | 100% | ||
strandharness | 0 | 495,175,368 | 100% | ||
whiskeynovelty | 0 | 495,149,144 | 100% | ||
smartcurator | 0 | 631,133,473 | 47.5% | ||
steem-ua | 0 | 493,016,437,903 | 4% | ||
semyuell | 0 | 496,073,430 | 100% | ||
nfc | 0 | 11,941,659,194 | 1% | ||
curbot | 0 | 3,914,621,410 | 10% | ||
viper777 | 0 | 478,528,606 | 100% | ||
bitok.xyz | 0 | 8,967,592,888 | 1% | ||
delabo | 0 | 33,346,266,338 | 25% | ||
whitebot | 0 | 38,027,642,063 | 2% |
Thank you for your contribution @duski.harahap. We've been reviewing your tutorial and suggest the following points below: - Again, we suggest you put comments in your code. It helps a lot to interpret the code. - We suggest that you name the parameters and the variables most perceptible. What is ```iat```? ``` { "sub": "1234567890", "name": "John Doe", "iat": 1516239022 } ``` <br/> Your tutorial is very well explained, again thanks for your work on doing these tutorials. 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/11111313). ---- 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/)
author | portugalcoin |
---|---|
permlink | re-duskiharahap-create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111-20181024t214909667z |
category | utopian-io |
json_metadata | {"tags":["utopian-io"],"users":["duski.harahap"],"links":["https://join.utopian.io/guidelines","https://review.utopian.io/result/8/11111313","https://support.utopian.io/","https://discord.gg/uTyJkNm","https://join.utopian.io/"],"app":"steemit/0.1"} |
created | 2018-10-24 21:49:09 |
last_update | 2018-10-24 21:49:09 |
depth | 1 |
children | 1 |
last_payout | 2018-10-31 21:49:09 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 5.854 HBD |
curator_payout_value | 1.880 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 978 |
author_reputation | 599,460,589,822,571 |
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 73,985,185 |
net_rshares | 6,803,305,472,698 |
author_curate_reward | "" |
voter | weight | wgt% | rshares | pct | time |
---|---|---|---|---|---|
yuxi | 0 | 8,881,674,684 | 30% | ||
mys | 0 | 4,985,824,453 | 3.96% | ||
utopian-io | 0 | 6,686,318,100,415 | 4.63% | ||
emrebeyler | 0 | 43,750,962,789 | 3% | ||
amosbastian | 0 | 19,314,807,726 | 9.1% | ||
indianteam | 0 | 54,189,624 | 9.1% | ||
reazuliqbal | 0 | 4,699,705,599 | 8% | ||
hakancelik | 0 | 14,972,148,984 | 20% | ||
statsexpert | 0 | 6,529,127,266 | 100% | ||
duski.harahap | 0 | 12,429,511,578 | 100% | ||
anonyvoter | 0 | 1,369,419,580 | 50% |
Thank you for your review, @portugalcoin! So far this week you've reviewed 7 contributions. Keep up the good work!
author | utopian-io |
---|---|
permlink | re-re-duskiharahap-create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111-20181024t214909667z-20181028t153521z |
category | utopian-io |
json_metadata | "{"app": "beem/0.20.9"}" |
created | 2018-10-28 15:35:24 |
last_update | 2018-10-28 15:35:24 |
depth | 2 |
children | 0 |
last_payout | 2018-11-04 15:35:24 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 115 |
author_reputation | 152,955,367,999,756 |
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 74,218,810 |
net_rshares | 0 |
#### 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)**
author | steem-ua |
---|---|
permlink | re-create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111-20181024t221345z |
category | utopian-io |
json_metadata | "{"app": "beem/0.20.7"}" |
created | 2018-10-24 22:13:48 |
last_update | 2018-10-24 22:13:48 |
depth | 1 |
children | 0 |
last_payout | 2018-10-31 22:13:48 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 292 |
author_reputation | 23,214,230,978,060 |
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 73,986,257 |
net_rshares | 0 |
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/payout.png?201810241619</td><td>You received more than 1000 as payout for your posts. Your next target is to reach a total payout of 2000</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/steemitboard/@steemitboard/steemitboard-ranking-update-resteem-and-resteemed-added"><img src="https://steemitimages.com/64x128/https://cdn.steemitimages.com/DQmfRVpHQhLDhnjDtqck8GPv9NPvNKPfMsDaAFDE1D9Er2Z/header_ranking.png"></a></td><td><a href="https://steemit.com/steemitboard/@steemitboard/steemitboard-ranking-update-resteem-and-resteemed-added">SteemitBoard Ranking update - Resteem and Resteemed added</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**!
author | steemitboard |
---|---|
permlink | steemitboard-notify-duskiharahap-20181025t155659000z |
category | utopian-io |
json_metadata | {"image":["https://steemitboard.com/img/notify.png"]} |
created | 2018-10-25 15:57:00 |
last_update | 2018-10-25 15:57:00 |
depth | 1 |
children | 0 |
last_payout | 2018-11-01 15:57:00 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 1,328 |
author_reputation | 38,975,615,169,260 |
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 74,035,263 |
net_rshares | 0 |
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>
author | utopian-io |
---|---|
permlink | re-create-restful-api-with-code-igniter-4-jwt-json-web-token-concept-login-function-and-decode-password-1540395859111-20181029t151511z |
category | utopian-io |
json_metadata | "{"app": "beem/0.20.9"}" |
created | 2018-10-29 15:15:12 |
last_update | 2018-10-29 15:15:12 |
depth | 1 |
children | 0 |
last_payout | 2018-11-05 15:15:12 |
cashout_time | 1969-12-31 23:59:59 |
total_payout_value | 0.000 HBD |
curator_payout_value | 0.000 HBD |
pending_payout_value | 0.000 HBD |
promoted | 0.000 HBD |
body_length | 595 |
author_reputation | 152,955,367,999,756 |
root_title | "Create RESTful API with Code Igniter #4 : JWT(JSON Web Token) Concept, Login function and Decode password" |
beneficiaries | [] |
max_accepted_payout | 1,000,000.000 HBD |
percent_hbd | 10,000 |
post_id | 74,282,407 |
net_rshares | 0 |