• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » PHP » PHP JSON Web Token Tutorial For Beginners

PHP JSON Web Token Tutorial For Beginners

By Sigit Prasetya Nugroho ∙ December 28, 2017 ∙ PHP ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

 

In this article, I will share tutorial what JSON Web Token is? How to implement JWT in PHP? How to create a client to access RESTFUL API using JWT token?

JWT or JSON Web Token is a long and randomly generated string token used to authenticate and exchange information. In the API concept, we can’t use SESSION as we do in PHP. But in the API method itself, we use the Token concept where we send the secret code through the header which will be interpreted by the server for data security. The official website is in jwt.io

Table of Contents

  • 1 How does JWT work?
  • 2 Tutorial Create JWT on PHP using firebase/PHP-JWT
    • 2.1 Why use firebase/PHP-JWT?
  • 3 Start PHP-JWT for beginners.
  • 4 Steps to use JSON Web Token on Slim Framework using PHP-JWT Library
  • 5 Create APP client to access RESTFUL API using JWT Authentication (PHP, JQUERY, And Angular)
    • 5.1 PHP tutorial to access the API using JWT Authentication
    • 5.2 The JQuery tutorial to access the Server APIs using JWT Authentication

How does JWT work?

JWT or Token is an encrypted password, so when users successfully login then the server will give a token. Then the Token will be stored by users on Local Storage or Cookies Browser and if the user wants to access certain page then must include the token. Then users will send back the tokens that have been given in advance as evidence if the user has been through the login process.

Token consists of three parts, namely

– header : contains algorithms and token types

1
2
3
4
{
  "alg": "HS256",
  "typ": "JWT"
}

– payload : information or data we want to send to users

1
2
3
4
5
{
  "exp": "2017-12-31",
  "name": "Sigit Prasetya Nugroho",
  "admin": true
}

– verify signature : the result of Hash or a combination of the contents of Header and Payload encode then added the secret code that you create

1
2
3
4
5
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  base64UrlEncode("IloveSeegatesite")
)

And the results of the three sections will be merged and automatically encoded into Token as follows.

1
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOiIyMDE3LTEyLTMxIiwibmFtZSI6IlNpZ2l0IFByYXNldHlhIE51Z3JvaG8iLCJhZG1pbiI6dHJ1ZX0.10vc7WE-Q05Z7w_-djz12Z9R1d3TJg1W57IQ1MX4pdg

The above tokens will be returned by the server and stored in local storage or browser cookies. Each time a user interacts with the API will include the token in the header (in general) or the post as authentication.

Tutorial Create JWT on PHP using firebase/PHP-JWT

Tutorial Php Jwt Authentication For Beginners Min

What is PHP-JWT? A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519.

Why use firebase/PHP-JWT?

Effective and efficient, you don’t have to bother creating scripts to generate JWT in PHP.

Installing firebase/php-jwt

1
composer require firebase/php-jwt

Start PHP-JWT for beginners.

After you install the PHP-JWT library above, the first step to make the JWT token is very easy. Here’s a simple example of creating a JWT token using PHP

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
require "vendor/autoload.php";
use \Firebase\JWT\JWT;
 
$secretkey = "example_keyssss";
$payload = array(
    "author" => "Sigit Prasetyo N",
    "authoruri" => "https://seegatesite.com",
    "exp" => time()+1000,
    );
try{
    $jwt = JWT::encode($payload, $secretkey);
    print_r($jwt);
}catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}
print_r('<br/>');
 
try{
    $decoded = JWT::decode($jwt, $secretkey, array('HS256'));
    print_r($decoded);
}catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}
 
?>

Explanation:

– In the payload section, there is variable “exp,” “exp” variable is used to record when token expires. “exp” is the date converted to time. If using PHP, you can use the time() function.

– Do not forget to use the try-catch function to encode and decode JWT token.

Next, I will apply JWT on Slim Framework to create a powerful RESTFUL API.

Steps to use JSON Web Token on Slim Framework using PHP-JWT Library

Installing slim framework using composer

1
composer create-project slim/slim-skeleton slimAPI

Installing firebase / PHP-JWT into the slimAPI folder

1
composer require firebase/php-jwt

For dummy data, I will create a JSON file containing the id and user along with the variable to store the token. Please create a db folder inside the slimAPI project folder and create a user.json file then fill in the following json script

1
2
3
4
{
"id":"1",
"user":"sigit",
"jwt":""}

Open the src folder then edit the middleware.php file and add the script.

1
2
3
4
5
6
7
8
9
10
11
<?php
// Application middleware
 
// e.g: $app->add(new \Slim\Csrf\Guard);
$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});

Open routes.php in the src folder and copy the following code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
 
use Slim\Http\Request;
use Slim\Http\Response;
use \Firebase\JWT\JWT;
 
$secretkey = "IloveSeegatesite";
 
function authGuard($jwt){
    global $secretkey;
    if(@$jwt['HTTP_AUTHORIZATION'][0]){
        $array = array();
        try {
            $decoded = JWT::decode($jwt['HTTP_AUTHORIZATION'][0], $secretkey, array('HS256'));
            $data = json_decode(json_encode($decoded),true);
            $json_file = file_get_contents('../db/user.json');
            $json_array = json_decode($json_file,true);
 
            if($data['id'] == $json_array['id'] and $data['user'] == $json_array['user'] and $jwt['HTTP_AUTHORIZATION'][0] == $json_array['jwt'])
            {
                $array[0]= true;
                $array[1]= 'secure';
            }else{
                $array[0]= false;
                $array[1]= 'invalid token';
            }
        }catch (UnexpectedValueException $e) {
            $array[0]= false;
            $array[1]= $e->getMessage();
        }
    }else{
        $array[0]= false;
        $array[1]= 'forbidden access';
    }
 
    return $array;
}
 
$app->get('/testJWT', function (Request $request, Response $response, array $args) {
 
    global $secretkey;
    $array = array();
    $data = $request->getHeaders();
    $guard = authGuard($data);
 
    return $response->withHeader('Content-type', 'application/json')
    ->withJson($guard);
});
 
$app->post('/authenticate', function (Request $request, Response $response, array $args) {
 
    //$data = $request->getParsedBody();
        $data = json_decode($request->getBody(),true);
    $post_id = $data['id'];
    $post_user = $data['user'];
 
    $json_file = file_get_contents('../db/user.json');
    $json_array = json_decode($json_file,true);
    // check id and user
    if($post_id == $json_array['id'] and $post_user == $json_array['user']){
        global $secretkey;
        $array = array();
        $payload = array(
            "id" => $post_id,
            "user"=> $post_user,
            "authoruri" => "https://seegatesite.com",
            "exp" => time()+(3600 * 24 * 1),
            );
 
        try{
 
            $array['status'] = true;
            $array['token'] = JWT::encode($payload, $secretkey);
 
            $dt = array();
            $dt['id'] = $post_id;
            $dt['user'] = $post_user;
            $dt['jwt'] = $array['token'];
 
            $fp = fopen('../db/user.json', 'w');
            fwrite($fp, json_encode($dt));
            fclose($fp);
 
        } catch (Exception $e) {
            $array['status'] = false;
            $array['token'] = $e->getMessage();
        }
    }else{
        $array['status'] = false;
        $array['token'] = 'User or id not found';
    }
 
    return $response->withHeader('Content-type', 'application/json')
    ->withJson($array);
});

A brief description :

– To get Token, please visit HTTP://localhost/slimAPI/public/authenticate with post id = 1 and user = sigit. When a post sent, it will get a response of a token that can be used as a key access to another API URL that requires a token as authentication. See the following gif

Using Jwt Authenticate In Php With Php Jwt

– After getting the token, save the token in PHP or local storage session or database. Then to test it using the token. Visit HTTP://localhost/slimAPI/public/testJWT by adding a parameter in the authorization header like the following gif image.

Php Jwt With Slim Framework For Beginner

If you already create a restful API with JWT, the next step we will make the client app to access the server.

Create APP client to access RESTFUL API using JWT Authentication (PHP, JQUERY, And Angular)

I will apply how to access the restful API using JWT Authentication on three different applications such as PHP, JQUERY and Angular 4

PHP tutorial to access the API using JWT Authentication

Copy the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
 
$post = array(
    'id' => 1,
    'user' => 'sigit',
    );
 
$data = json_encode($post);
 
$ch = curl_init('http://localhost/slimAPI/public/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
// curl_setopt($ch, CURLOPT_POSTFIELDS,"id=1&user=sigit");
// curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
 
$response = curl_exec($ch);
curl_close($ch);
$data    = json_decode($response,true);
 
echo 'JWT Key : '.$data['token'];
 
echo '<br/>';
echo '<br/>';
 
$ch = curl_init('http://localhost/slimAPI/public/testJWT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: '.$data['token']));
$response = curl_exec($ch);
curl_close($ch);
echo 'Response : ';
echo '<br/>';
print_r($response);
?>

The JQuery tutorial to access the Server APIs using JWT Authentication

Copy the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html>
<head>
    <title>Test Jquery JWT Token</title>
</head>
<body>
    <button id="gettoken">Authenticate</button>
    <div id="result1"></div>
    <script
    src="https://code.jquery.com/jquery-2.2.4.min.js"
    integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
    crossorigin="anonymous"></script>
    <script type="text/javascript">
        $("#gettoken").click(function(){
            var value = JSON.stringify({
                id:1,
                user:"sigit"
            });
            $.ajax({
                url: "http://localhost/slimAPI/public/authenticate",
                type: 'POST',
                contentType: 'application/json',
                dataType: "json",
                data:value ,
                success: function(data, textStatus, jqXHR){
                    $("#result1").html('JWT Token : '+data.token+'<br> <br> <button id="testapi" data-token='+data.token+'>Test API</button> <div id="result2"><div>');
                },
            })
        })
        $(document).on("click","#testapi",function(){
            var token = $(this).attr("data-token");
            $.ajax({
                url: "http://localhost/slimAPI/public/testJWT",
                type: 'GET',
                beforeSend: function(request) {
                    request.setRequestHeader("Authorization", token);
                },
                success: function(data, textStatus, jqXHR){
                    $("#result2").html(data[0]+"<br>"+data[1]);
                },
            })
        })
    </script>
</body>
</html>

For implementation with Angular 4, I will give a piece of the program from the project I’m working on, so it’s not related to the API example above. Here’s my code accessing API Server using JWT Authentication on Angular 4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { Injectable } from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
 
@Injectable()
export class DataService {
  private serverpath: string = 'http://192.168.1.20/invent/api/';
 
  constructor(private http: Http) { }
  // header rest
  private getHeaders() {
 
    let headers = new Headers();
    if (localStorage.getItem('currentUser')) {
      var xcs:any = JSON.parse(localStorage.getItem('currentUser'));
      headers.append('Authorization', xcs.authorization);
    }
    headers.append('Accept', 'application/json');
    return headers;
  }
  // sistem service
  login(post): Observable<any> {
    const getLoginPath = this.serverpath + 'get/login/' + post['txtuser'] + '/' + post['txtpass'];
    return this.http.get(getLoginPath, {headers: this.getHeaders()})
      .map(
      res => {
        if (res.json().status == true) {
          localStorage.setItem('currentUser', JSON.stringify(res.json().data));
        }
        return res.json();
      },
      err => {
        return err;
      }
      )
  }
  getDaftarKantor(): Observable<any> {
    const url = this.serverpath + 'get/daftar_kantor';
    return this.http.get(url, {headers: this.getHeaders()})
      .map(
      res => {
        return res.json();
      },
      err => {
        return err;
      }
      )
  }

To download the source code sample of RESTFUL API project With PHP-JWT And How to Access it, please download through the following link. To open the download link, please share this article through the button that has been provided.

[sociallocker id=”58″]
Url: https://seegatesite.com/tutorial-php-restful-api-with-jwt-authentication-for-beginners-source-code-project/
[/sociallocker]

So my tutorial on PHP JSON Web Token Tutorial For Beginners may be useful

Another PHP Related Post :

  • Tutorial Create Simple POS Using ReactJS And Laravel Lumen Part 1
  • How To Replace String With Another String In PHP
  • Login Page – Tutorial CRUD Client and API Server Using JQuery And Lumen Part 2
  • Tutorial CRUD Client and API Server Using JQuery And Lumen Part 1
  • How To Solve Problems Illegal mix of collations (latin1_swedish_ci,IMPLICIT) In Laravel
  • How To Resolve No ‘Access-Control-Allow-Origin’ Header In Lumen

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) lumen api (4) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (8) Publisher Tips (5) react (6) Reactjs (9) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2022 Seegatesite.com