Secure api endpoints using tokens php jwt 2022

    By: Manu
    2 years ago
    Category: PHPViews: 546

    So securing api is something most important part. Now we can add authentication to verify if the endpoints are accessed by correct audience. So using swagger we do that. Follow below given steps:


    Step 1 -> If you need premade api project try here

    Step 2 -> How to add swagger into your api application check here

    Step 3 -> Implementing authentication that we do now


    In project file on top we need to add annotation to enable swagger security feature

    <?php
    
    
    error_reporting(E_ALL);
    ini_set('display_error', 1);
    
    
    require($_SERVER['DOCUMENT_ROOT'].'/test/vendor/autoload.php');
    
    
    use Firebase\JWT\JWT;
    use Firebase\JWT\Key;
    
    
    /**
     * @OA\Info(title="PDO PHP REST API", version="1.0")
     *    @OA\SecurityScheme(
     *        type="http",
     *        description="Authorisation with JWT generated tokens",
     *        name="Authorization",
     *        in="header",
     *        scheme="bearer",
     *        bearerFormat="JWT",
     *        securityScheme="bearerToken"
     *    )
     */
    

    Notice we are using PHP-JWT Install it

    composer require firebase/php-jwt
    

    read more about PHP-JWT


    Now in model "Post" to enable swagger lock on each end point we need to add this

     /**
         * @OA\Get(
         *     path="/test/api/post/posts.php",
         *     summary="Method to read all the saved posts from database.",
         *     tags={"Posts"},
         *     @OA\Response(response="200", description="An example resource"),
         *     @OA\Response(response="404", description="Not Found"),
         *     security={ {"bearerToken": {}}                                <----- This line but do not add this in auth function.
         * )
         */
    

    This will show a lock next to endpoint in swagger.

    For authenticating route we can add code logic as

     $headers = apache_request_headers();
               
               if(isset($headers['Authorization']))
               {
                  $token = str_ireplace('Bearer ', '', $headers['Authorization']);
                  
                  $decoded = JWT::decode($token , new Key($this->key, 'HS256'));
    
    
                    if(isset($decoded->userName) && $decoded->userName == 'Roger max')
                    {
                        // User allowed here
                    }
                   // User not allowed here
                } 
             
    

    Check video guide for better understanding...