jwt-auth icon indicating copy to clipboard operation
jwt-auth copied to clipboard

Token invalid | Token Signature could not be verified.

Open Fabiantjoeaon opened this issue 7 years ago • 19 comments

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?

Fabiantjoeaon avatar Nov 18 '16 21:11 Fabiantjoeaon

+1

anilskalyane avatar Nov 28 '16 13:11 anilskalyane

I noticed vendor\tymon\jwt-auth\src\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.

Lauriy avatar Dec 06 '16 09:12 Lauriy

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'),
                ],
            ]
        );

Lauriy avatar Dec 06 '16 10:12 Lauriy

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.

MitchellMcKenna avatar Jan 16 '17 19:01 MitchellMcKenna

Thanks for the tip.

Lauriy avatar Jan 17 '17 09:01 Lauriy

@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.

lednhatkhanh avatar Mar 07 '17 10:03 lednhatkhanh

"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

NaPsTeRScofielD avatar Mar 18 '17 05:03 NaPsTeRScofielD

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

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

Lauriy avatar Mar 18 '17 09:03 Lauriy

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)

`

NightravenJames avatar Jul 19 '17 09:07 NightravenJames

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"
    },

elliottjro avatar Jul 28 '17 20:07 elliottjro

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

jameybay avatar Jul 31 '17 19:07 jameybay

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

james2doyle avatar Oct 31 '17 21:10 james2doyle

I solve this issue running

php artisan jwt:secret

casivaagustin-zz avatar Nov 22 '17 20:11 casivaagustin-zz

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

santiagazo avatar Dec 12 '17 21:12 santiagazo

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

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

kevinfszu avatar May 21 '20 08:05 kevinfszu

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.

stale[bot] avatar Dec 25 '20 17:12 stale[bot]

I had been experiencing this issue as well. However I clear my browser cookies and it works.

  1. Open Developer Tools (usually F12)
  2. Click the "Application" tab
  3. Expand the "Cookies" list item
  4. clear

zhonglangjp avatar Apr 07 '22 03:04 zhonglangjp

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?

I had been experiencing this issue as well. However I clear my browser cookies and it works.

  1. Open Developer Tools (usually F12)
  2. Click the "Application" tab'
  3. Expand the "Cookies" list item
  4. Clear cookies

zhonglangjp avatar Apr 07 '22 03:04 zhonglangjp

Here same issue: i get randomly Token Signature could not be verified. (but token validation performed with jwt debugger are correct). Here the stack:

Tymon\JWTAuth\Exceptions\TokenInvalidException Token Signature could not be verified. 
    vendor/tymon/jwt-auth/src/Providers/JWT/NamshiAdapter.php:71 Tymon\JWTAuth\Providers\JWT\NamshiAdapter::decode
    vendor/tymon/jwt-auth/src/JWTManager.php:79 Tymon\JWTAuth\JWTManager::decode
    vendor/tymon/jwt-auth/src/JWTAuth.php:190 Tymon\JWTAuth\JWTAuth::getPayload
    vendor/tymon/jwt-auth/src/JWTAuth.php:124 Tymon\JWTAuth\JWTAuth::authenticate
    app/Providers/RouteServiceProvider.php:36 App\Providers\RouteServiceProvider::boot
    [internal] call_user_func_array
    bootstrap/cache/compiled.php:1257 Illuminate\Container\Container::call
    bootstrap/cache/compiled.php:1899 Illuminate\Foundation\Application::bootProvider
    bootstrap/cache/compiled.php:1891 Illuminate\Foundation\Application::Illuminate\Foundation\{closure}
    [internal] array_walk
    bootstrap/cache/compiled.php:1892 Illuminate\Foundation\Application::boot
    bootstrap/cache/compiled.php:2231 Illuminate\Foundation\Bootstrap\BootProviders::bootstrap
    bootstrap/cache/compiled.php:1666 Illuminate\Foundation\Application::bootstrapWith
    bootstrap/cache/compiled.php:2412 Illuminate\Foundation\Http\Kernel::bootstrap
    bootstrap/cache/compiled.php:2365 Illuminate\Foundation\Http\Kernel::sendRequestThroughRouter
    bootstrap/cache/compiled.php:2350 Illuminate\Foundation\Http\Kernel::handle
    public/index.php:53 [main]

A pretty old project, i know...

"laravel/framework": "5.2.*",
"tymon/jwt-auth": "0.5.*",

emacaste avatar Feb 03 '23 08:02 emacaste