Francis
Francis

Reputation: 495

Laravel 7.0 - tymon/jwt-auth - check if token is valid

Trying to achieve a login endpoint at a laravel installation by using tymon/jwt-auth (JWT). The login, logout, get userdata is working fine. I would like to have a endpoint for checking the Bearer Token. There is a short way to achieve this via:

Route::get('/valid', function () {
    return 1;
})->middleware('auth:api');

If the token is valid, the the HTTP return code == 200 but if not, a 401 code is returned. Since the endpoint is checking a token and not the authenticated communication, I would like to rather have a controller returning true/false regarding valid token with 200 - OK.

I had a look "under the hood" of the modules and that is how far I get (not working):

            $tokenKey = $request->bearerToken();
            $jws = \Namshi\JOSE\JWS::load($tokenKey);

            $jwsSimple = new SimpleJWS($jws->getHeader());
            $jwsSimple::load($tokenKey);
            $jwsSimple->setPayload($jws->getPayload());
            $jwsSimple->setEncodedSignature(explode('.', $tokenKey)[2]);

            $tmpVal = $jwsSimple->isValid($tokenKey);

Is there any better approach to achieve this? I assume that there should be a Service Provider for that but could not figure out how to implement this. Thank you in advance.

Upvotes: 2

Views: 18719

Answers (4)

Francis
Francis

Reputation: 495

// Validate Token Controller:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ValidTokenController extends Controller
{
    public function __invoke(Request $request)
    {
        $response = auth('api')->check();
        $responseCode = 200;
        if(!$response) {
            try {
               if (!app(\Tymon\JWTAuth\JWTAuth::class)->parseToken()->authenticate()) {
               $response = 0;
               }
            } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
               $response = -1;
            } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
               $response = -2;
            } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
               $response = -3;
            }
        } else {
            $response = (int) $response;
        }
        return response()->json($response, $responseCode);
    }
}

Upvotes: 0

Francis
Francis

Reputation: 495

Here is the mixed output to achieve status based token validation with laravel and tymon/jwt-auth:

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class ValidTokenController extends Controller
{
    public function __invoke(Request $request)
    {
        $response = (int) auth('api')->check();
        $responseCode = 200;
        try {
            if (!app(\Tymon\JWTAuth\JWTAuth::class)->parseToken()->authenticate()) {
                $response = 0;
            }
        } catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
            $response = -1;
        } catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
            $response = -2;
        } catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
            $response = -3;
        }
        return response()->json($response, $responseCode);
    }
}

Upvotes: 1

GTCrais
GTCrais

Reputation: 2077

You could remove the auth:api middleware and then have something like:

return response()->json([ 'valid' => auth()->check() ]);

Upvotes: 12

Maybe this method need you:

public function getAuthenticatedUser()
            {
                    try {

                            if (! $user = JWTAuth::parseToken()->authenticate()) {
                                    return response()->json(['user_not_found'], 404);
                            }

                    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

                            return response()->json(['token_expired'], $e->getStatusCode());

                    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

                            return response()->json(['token_invalid'], $e->getStatusCode());

                    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

                            return response()->json(['token_absent'], $e->getStatusCode());

                    }

                    return response()->json(compact('user'));
            }

Upvotes: 3

Related Questions