Build Rest API in Slim Microframework part-2 (JWT)

in #utopian-io6 years ago (edited)

Screenshot_4.png

This tutorial I will discuss JSON (JSON Web Token). JWT brings a familiar concept to those of you who often play with APIs, our JWT system wraps data in tokens. so any action that requires authentication we attach the token to match with the tokens in the serve. and here I will use it on Slim. how to do it, we just start this tutorial. Because this tutorial is a continuing series of Slim API, I suggest you follow the tutorial series I put in the curriculum.

What Will I Learn?

  • Use Postman for JWT
  • Use JWT for user token
  • Make response JSON
  • Encode data to JWT

Requirements

  • Composer
  • Package firebase/JWT
  • Localhost (Xampp, Wampp or etc)
  • Slim
  • Intermediate OOP PHP

Difficulty

  • Intermediate

Preparation

The first step we have to install package from firebase / JWT. we install from composer.json, open the command prompt in your project.

composer require firebase/php-jwt

Screenshot_31.png

If there is no error then you will the see in the composer. firebase / JWT has been registered. if something goes wrong please check your internet connection.

Make API for JWT

Then we will create a fire route to point to the login which we will use JWT for user authentication system. Open the web.php file located in the routes folder.

  • Make Route Api
  • 
    <?php
    $app->group('/api',function(){
    $this->post('/login', 'App\controllers\userController:login');
    });
    
    
    $app->group('/api',function(){} : We create a group route to make it look neater and elegant, so later on every fire-related routing, we'll create a prefix /api

    $this->post('/login', 'App\controllers\userController:login'); We use the method post because We do not want the information to be seen. : /login is the name of the route we will use for the system login and userController is the name of the controller that functions responsible for the login function.

  • Make Model User
  • In the previous tutorial I have created a users table in the database. but I will show the folder structure again.

    Database

    NameTypeLength/valueIndeks
    idINT100Primary
    usernameVarchar100--
    passwordVarchar100--

    INSERT INTO forum.users (id, username, passoword) VALUES (NULL, 'jhon doe', 'pass123'), (NULL, 'Helewt arold', 'pass1234');

    Model user.php

    
    <?php
    namespace App\models;
    use Illuminate\Database\Eloquent\Model;
    class user extends model {
    protected $table = "users";
    }
    
    
  • Make userController
  • Well after that we will create userController.php, which will be responsible for handling user functions.
    
    <?php
    use App\models\user;
    class userController
    {
    protected $c;
    public function __construct(ContainerInterface $container){
    $this->c = $container;
    }
    public function login($request,$response){
    var_dump($request->getParsedBody());
    }
    }
    
    
    protected $c; : Provide a variable that will be used later to accommodate $container. I will put the container in the __construct function. __Construct is the function that will first be called.

    var_dump($request->getParsedBody()); : I will make a little test in here. I will see the contents of $request, using getParsedBody(), So we can see the contents of the body we have sent from the postman.

  • Use Postman to send databody
  • I will use postman to send data through body by post method. ![Screenshot_3.png]()

    URL: is the URL of the API we have created, we pair with POST method so that the data we send can't be seen.

    x-www-urlencoded : If using post method we provided body to send data like in website.

    Key and Value: We input user data in the user database we have created earlier.

    Result of the body: Because in the controller we use var_dump to see the power form that we send through postman, so the result we will see in the form of an array.

    Generate Token JWT

    We will create a function to generate JWT token, this is the code from userController.php

    
    <?php
    namespace App\Controllers;
    use Interop\Container\ContainerInterface;
    use App\models\user;
    use \Firebase\JWT\JWT;
    class userController
    {
    protected $c;
    public function __construct(ContainerInterface $container){
    $this->c = $container;
    }
    private $key = "secretkey";
    public function login($request,$response){
    $username = $request->getParsedBody('username');
    $password = $request->getParsedBody('password');
    $user = user::where('username',$username)->where('password',$password )->first();
    if(empty($user)){
    return $response->withJson([
    'success' => false,
    'message' => "Username or Password false"
    ]);
    }
    $token = [
    "iss" => "utopian",
    "iat" => time(),
    "exp" => time() + 60,
    "data" => [
    "user_id" => $user->id
    ]
    ];
    $jwt = JWT::encode($token, $this->key);
    return $response->withJson([
    'success' => true,
    'message' => "Login Successfull",
    'jwt' => $jwt
    ]);
    }
    }
    
    
  • Use Package JWT add setting
  • We have installed firebase / jwt, now we will use it in userController.php in this way.

    Use Package JWT

    use \Firebase\JWT\JWT;

    Set Secret Key

    private $key = "secretkey"; : This must be unique but in case i simple added string "secretkey" .

    Make Variable from Body

    
    $username = $request->getParsedBody('username');
    $password = $request->getParsedBody('password');
    
    
    We can get value and keep in the variable , so we can use in another code block.

    Find user
    $user = user::where('username',$username)->where('password',$password )->first();
    We can add some logic and We can match the data that is in the body with the existing data in our database, as the initialization table using the user::.

    Make validate user

    
    if(empty($user)){
    return $response->withJson([
    'success' => false,
    'message' => "Username or Password false"
    ]);
    }
    
    
    We can add simple logic if username and password are wrong if(empty($user)),Then we will return response message error.


    Create Token

    
    $token = [
    "iss" => "utopian",
    "iat" => time(),
    "exp" => time() + 60,
    "data" => [
    "user_id" => $user->id
    ]
    ];
    
    
    I store the token in the $token variable. "iss" => "utopian", : It's issuer . The person who issued the token.

    "iat" => time(), : It's issue at , The time when this token was created, I make time() it's mean this time.

    "exp" => time() + 60, : The expired token , Units in minutes.

    "data"=>["user_id" => $user->id] : The data you want to add , in this case i just add the user_id , the value from $user->id.

    Generate Token

    Then we can generated tokens in this way :

    $jwt = JWT::encode($token, $this->key);

    We have two parameters, the first is the data token, and the second is the secret key that we created earlier in the $key.

    Return JWT

    
     return $response->withJson([
      'success' => true,
      'message' => "Login Successfull",
      'jwt' => $jwt
      ]);
    
    
    And finally we can return the response token that has been successfully generated.

    We can open the Xampp to run localhost and open the Postman to show the result.

    Screenshot_4.png

    and finally, we can see the result of the generated token that we have successfully created, so much of me. hopefully, this tutorial can help you thank you. if you get confused, you can see my previous tutorial series.

    Curriculum

  • - Templating Twig in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-use-twig-templating-in-slim
  • - Eloquent in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-use-database-eloquent-in-slim
  • - Routing System in Slim https://utopian.io/utopian-io/@alfarisi94/how-to-install-slim-and-basic-routing-system-in-slim
  • - Slim MVC Part-1 https://utopian.io/utopian-io/@alfarisi94/create-mvc-model-view-controller-structure-in-slim-microframework-part-1
  • - Slim MVC Part-1 https://utopian.io/utopian-io/@alfarisi94/create-mvc-model-view-controller-structure-in-slim-microframework-part-2
  • - Slim API Part-1 https://utopian.io/utopian-io/@alfarisi94/build-rest-api-in-slim-microframework-part-1


  • Posted on Utopian.io - Rewarding Open Source Contributors

    Sort:  

    Your contribution cannot be approved because it does not follow the Utopian Rules.

    • The writing style should be formal and informative.
    • The writing style should be professional and clear.
    • Only contribution posts written in plain and easily understood English will be accepted.
    • Quoting @yokunjon: "A tutorial must be informative and explanatory, but also "tutor". This tutorial lacks "tutor"ing and it is nothing more than "Do whatever I do." kind of tutorial."

    You can contact us on Discord.
    [utopian-moderator]

    Hey @miguepersa, I just gave you a tip for your hard work on moderation. Upvote this comment to support the utopian moderators and increase your future rewards!

    What the means writing styel should be professional and clear, could you make a example? Where the the part is not understood??

    Coin Marketplace

    STEEM 0.20
    TRX 0.14
    JST 0.030
    BTC 67408.93
    ETH 3491.49
    USDT 1.00
    SBD 2.70