Loading

Validate JWT Token In Lumen

Validate JWT Token In Lumen

In Lumen we all are familier with its authentication process. Recently, I am in a situation where I have to validate my JWT token externally.

Normally you first send your username and password at the very begining and based on that credential it returns you a token. Everytime you sends a request you need to send that token within header. If that token is invalid or expire it will automatically throws the exceptions.

But what if you just need a method which only tells whether your token is valid or not? That brings me to find out a way how to validate a JWT token in Lumen and this article is for that particular solution.

So, lets see how this can be achive...

Step 1

First, create an endpoint in Routes


$router->get('/auth/validateToken', 'AuthController@validateToken');

Step 2

Now in Auth Controller, we have to write this method

public function validateToken(Request $request)
    {
        $token = '';
        try {
            $tokenFetch = $this->jwt->parseToken()->authenticate();
            if ($tokenFetch) {
                $token = str_replace("Bearer ", "", $request->header('Authorization'));
            } else {
                $token = 'Token Not Found';
            }
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            $token = 'Token is invalid or expired';
        }
        return $token;
    }

Step 3

Now its time to check how this works. I am using Postman in this case. lumenAuth.jpg

Summary

So, by this, you can see how we can validate the token outside from the application using Postman. Is it useful to you? If so, please leave a comment at info@codinghub.net and share this article as much as you can.

To check out more Lumen articles, you can take a look at Lumen Installation or Creating a REST API with Lumen.

We are on Facebook, Twitter, LinkedIn, Medium, Quora, Instagram, etc.

By the way, want to learn more about Lumen? Just check out the official Lumen documentation.

Related Articles