Jwt-auth: Token invalid | Token Signature could not be verified.

Created on 18 Nov 2016  路  16Comments  路  Source: tymondesigns/jwt-auth

I'm getting pretty tired of this error.. Stuck for 2 days now.

I do receive a token on valid credentials, but my token stays invalid, no matter if I pass it through url parameter (?token=[token]) or as Auth header (Bearer: [token]).
Anyone still experiencing this? I followed everything in the tutorial. Also configured both .htaccess in my public folder, and in my apache configuration.

  Route::get('/test', function () {
    return JWTAuth::parseToken()->authenticate();
  });

Going to this route returns

TokenInvalidException in NamshiAdapter.php line 71:
Token Signature could not be verified.

For lookups, here is my authentication method from my AuthController.php

  public function authenticate(Request $request) {
    $credentials = $request->only('email', 'password');

    $user = User::where('email', Input::get('email'))->first();

    try {
      if (!$token = JWTAuth::attempt($credentials)) {
        return $this->respondUnauthorized();
      }
    } catch (JWTException $e) {
        return $this->respondInternalError('Could not create token!');
    }
    // dd()
    return $this->respond([
      'token' => compact('token'),
      'user' => $user]);
  }

My routes middleware group:
Route::group(['middleware' => ['jwt.auth', 'jwt.refresh']], function() {

There must be something wrong? Is this just a minor bug or am I missing something?

stale

Most helpful comment

I had been experiencing this issue as well, however I discovered the issue is having a colon : after bearer is actually not supported. Remove that from your Authorization header and you should be good to go.

All 16 comments

+1

I noticed vendor\tymon\jwt-authsrc\Providers\JWT\Namshi.php decode function takes in my token as:
": eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJuYW1lIjoiTGF1cmkgRWxpYXMiLCJleHAiOjE0ODE4ODE0NjV9.PgENjq9vuTeijRrPIXIyc1ioFE1DoEzPikMZlZYsO7eJepRqj5SN354glSjqi2ozaYC2HQ1m2egi_WxH3tFifqefwhAeBAiHOuOTGQ9ZpDOUKWlM-ld8P4m3h0qEwg5hFPJ03r7lmjBKzxfU7rWPaeL3cmEOlfX4OWGRXAdUvcs"
(notice the colon and space)

If I add a rather blunt workaround:

        if ($token[0] == ':' && $token[1] == ' ') {
            $token = substr($token, 2);
        }

My tests go green.

Went with this for now:

<?php

namespace App\Providers;

use InvalidArgumentException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Providers\JWT\Namshi;

class BugfixedNamshiProvider extends Namshi
{
    /**
     * Decode a JSON Web Token.
     *
     * @param  string $token
     *
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     *
     * @return array
     */
    public function decode($token)
    {
        // Fix bug with jwt-auth package
        if ($token[0] == ':' && $token[1] == ' ') {
            $token = substr($token, 2);
        }

        try {
            // Let's never allow insecure tokens
            $jws = $this->jws->load($token, false);
        } catch (InvalidArgumentException $e) {
            throw new TokenInvalidException('Could not decode token: ' . $e->getMessage(), $e->getCode(), $e);
        }

        if (!$jws->verify($this->getVerificationKey(), $this->getAlgo())) {
            throw new TokenInvalidException('Token Signature could not be verified.');
        }

        return (array) $jws->getPayload();
    }
}

And in jwt.php config file:

    'providers' => [
        'jwt' => BugfixedNamshiProvider::class,
        'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
        'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
    ],

And in tests:

        $namshi = app()->make(
            BugfixedNamshiProvider::class,
            [
                null,
                'RS256',
                [
                    'public' => config('jwt.keys.public'),
                    'private' => config('jwt.keys.private'),
                ],
            ]
        );

I had been experiencing this issue as well, however I discovered the issue is having a colon : after bearer is actually not supported. Remove that from your Authorization header and you should be good to go.

Thanks for the tip.

@MitchellMcKenna Hello, I'm facing this problem as well, could you please provide the details for the fix. I'm not so familiar with laravel. Thank you.

"setting the api secret in jwt.php"

in fact on config/jwt.php, there is the line'secret' => env('JWT_SECRET'),,

Generate the key with this helper php artisan jwt:generate (for some reason I dont know why it doesnt set in the .env file itself like php artisan key:generate).
Copy the key (jwt-auth secret [DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9] set successfully.) without the bracket and add it in .env file like JWT_SECRET=DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9 or you can change it straigth in jwt.php secret' => env('DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9')

remember to have your .env file in your project if you dont have do php -r "copy('.env.example', '.env');" and php artisan key:generate

env('DSvO98YtJ0204mBu9zqWN9QOMX7Tmvr9') <- remove the env() function then.

Also, there are installation instructions here: https://github.com/tymondesigns/jwt-auth/wiki/Installation

Followed this link https://github.com/tymondesigns/jwt-auth/wiki/Installation but when it comes to the getting the authenticated user am getting . The following error
`

TokenInvalidExceptionToken Signature could not be verified.

in聽NamshiAdapter.php聽(line 71)

`

Hey all.. for some reason this started working when I changed my auth header to be bearer TOKEN ie:

key:
Authorization
value:
bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIU......Vlqb0AjEds

Previously I used bearer{djjdnskaF93jasdf.....FDSaM} - using the brackets { } - which was throwing this error.

My composer.json:

"require": {
        "php": ">=5.6.4",
        "doctrine/dbal": "^2.5",
        "facebook/graph-sdk": "^5.4",
        "folklore/graphql": "~1.0.0",
        "guzzlehttp/guzzle": "^6.3",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0",
        "predis/predis": "^1.1",
        "tymon/jwt-auth": "0.5.*",
        "webpatser/laravel-uuid": "^2.0"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.7"
    },

Thanks so much. Removing the brackets '{}' worked.

I was getting this in Laravel 5.5 randomly. I ran php artisan key:generate and it was gone.

I solve this issue running

php artisan jwt:secret

@ElliottJRo Man thanks so much! removing the brackets in postman worked for me!

Thanks so much. Removing the brackets '{}' worked.

This saves me. I'm so stupid to misunderstanding the {} in the official documents.

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

phamduong picture phamduong  路  3Comments

harveyslash picture harveyslash  路  3Comments

kofi1995 picture kofi1995  路  3Comments

johncloud200 picture johncloud200  路  3Comments

aofdev picture aofdev  路  3Comments