Jwt-auth: Check if Token exists & is valid

Created on 30 Sep 2015  路  2Comments  路  Source: tymondesigns/jwt-auth

I want to detect in my Controller if a token that is passed to a Route (that does not require Authentication) is valid.

$headerAuth = $request->header('Authorization');
if ($headerAuth) {
    if ($tokenFetch = JWTAuth::parseToken()->authenticate()) {
        $token = str_replace("Bearer ", "", $request->header('Authorization'));
    } else {
        $token = '';
    }
} else {
    $token = '';
}

If I try the script above with a valid Token, it works and returns $token = str_replace("Bearer ", "", $request->header('Authorization'));

But if I send an invalid Token I get an error:

TokenInvalidException in NamshiAdapter.php line 62:

Token Signature could not be verified.

Is there another way of checking if a token has been passed and if it is actually valid?

Most helpful comment

@tymondesigns Thanks. I've altered my code for the moment to the following

        try {
            $tokenFetch = JWTAuth::parseToken()->authenticate();
            if ($tokenFetch) {
                $token = str_replace("Bearer ", "", $request->header('Authorization'));
            } else {
                $token = '';
            }
        } catch(\Tymon\JWTAuth\Exceptions\JWTException $e){//general JWT exception
            $token = '';
        }

All 2 comments

There will be a jwt.check middleware for this in the new version, if you can wait a little

@tymondesigns Thanks. I've altered my code for the moment to the following

        try {
            $tokenFetch = JWTAuth::parseToken()->authenticate();
            if ($tokenFetch) {
                $token = str_replace("Bearer ", "", $request->header('Authorization'));
            } else {
                $token = '';
            }
        } catch(\Tymon\JWTAuth\Exceptions\JWTException $e){//general JWT exception
            $token = '';
        }
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gamelife1314 picture gamelife1314  路  3Comments

agneshoving picture agneshoving  路  3Comments

therealmjk picture therealmjk  路  3Comments

loic-lopez picture loic-lopez  路  3Comments

aofdev picture aofdev  路  3Comments