Jwt verify не работает

jwt.verify() returns jwt expired when the expiration is 24h

I used jwt to create a token:

When I test the snippet code mentioned above in my real app, I got an error message:

Using the jwt debugger, the token is valid and should expire after 24h. The error returned by verify() which checks the expiration. How jwt checks the expiration? or it does not check it?

1 Answer 1

So since the question is, how does jwt check the expiration date, it depends on basically on some properties that may be implemented according to the JWT RFC

One would be exp . In case a token expires before the current datetime, then the JWT cannot be processed

The «exp» (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the «exp» claim requires that the current date/time MUST be before the expiration date/time listed in the «exp» claim.

Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

Another one to note would be the iat , which stands for issued at

The «iat» (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

A final one that could be used for time verfication, as far as I am aware of would be, nbf , standing for not before

The «nbf» (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the «nbf» claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the «nbf» claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.

Now, for the code at hand, I don’t see anything which is of, having following setup, this works perfectly fine for me

which would output

This can be validated on the codesandbox link


JWT verification error: JsonWebTokenError: invalid algorithm

i am trying to implement a single sign on for my web application. I am using gravitee.io for the access managment and token generation. I followed the steps in gravitees quickstart tutorial and i am now at the point that i want to verify my id_token.

In order to do that i am using the node-jsonwebtoken library. i am using total.js for my backend (which should not be as important, but i still wanted to mention it).

What i have done so far. i have my client-id and my client-secret as well as my domain secret in the total.js config file

./configs/myconfig.conf (key/secret is changed)

i added a model to handle the login workflow for total.js in order to get the jwt tokens from gravitee by REST-call. So far everything works as expected. a session is created and stores the response in it. the gravitee response is the expected json which looks like this

I split up the tokens in seperate cookies because when i tried to save them as a single cookie, i got an error that told me the cookie exceeds the 4096 length limit.

So far everything works just fine. in the frontend ajax call the success callback will be executed, just setting the window.location.href=’/’; to call the dashboard of my application. I set this route to be accessible only when authorized, so that when my dashboard is called, the onAuthorize function is called by totaljs.

I also tried to just send the CONFIG(‘client-secret’) without buffering. I also tried to send the CONFIG(‘domain-public-key’) . But the error i get is always the same:

When i copy and paste the id_token into the debugger at jwt.io with algorithm beeing set to RS256 i’ll see the following decoded values:

i copied the public key from my domain in to the respective textfield and i also tried to use the client-secret. no matter what i do, the error i am getting here is

Warning: Looks like your JWT signature is not encoded correctly using base64url (https://www.rfc-editor.org/rfc/rfc4648#section-5). Note that padding («=») must be omitted as per https://www.rfc-editor.org/rfc/rfc7515#section-2

I dont understand why there is an algorithm error when i try to verify the token in my backend and some encoding error at jwt.io debugger.

can somebody explain to me on how to fix the issue? Thanks in advance Pascal


JWT (JSON Web Tokens) Errors | Invalid JWT Signature

Errors are the best especially when they are written in a way where you become a decipherer. I remember the good old days when all the error codes I got were only numbers and maybe letters mixed in and there wasn’t any online searching to easly get interpretations.

I’ve been working with Google Cloud products and connecting to services from my laptop like Storage and BigQuery. Over the last several months, I’ve hit up against a JWT error, invalid_grant:Invalid JWT Signature , a couple times, and below provides an overview of how I resolved it, which was basically updating the expired service account key.

JWT Errors

“The mechanics of server-to-server authentication interactions require applications to create and cryptographically sign JSON Web Tokens (JWTs).” JWTs are signed tokens to authenticate your server to server connections.

This page on Using OAuth 2.0 for Server to Server Applications has a section in the middle called JWT error codes which gives more details about the different errors you may see and how to resolve them. Its a good place to start for more information.

Читайте также:  Как открыть капот если сломалась пружинка

Invalid JWT Signature: invalid_grant

For my error, invalid_grant:Invalid JWT Signature , the way to resolve wasn’t included in the list under JWT error codes. Basically, the Service Account key expired, and I needed to generate a new one.

I did find someone in a StackOverflow thread who helped me hone in on this with this comment: The JWT assertion is signed with a private key not associated with the service account identified by the client email.

I thought for a moment the email under my local gcloud config might be the problem, but it ended up being the expired key. Thus, the key was not associated with the service account anymore.

How to Fix | Adding New Service Account Key

In order to fix this, go to the APIs & Services on the Google Cloud Console.

Look under Service Accounts, for the email account you are using for your project.

If you don’t remember what that email address is then you can look it up with the command.

On Google Cloud Console, choose the edit symbol next to that email account you are using.

Choose the Keys section.

Check if your service account key is Active or Expired.

If you don’t know what the service account key is that you are using, look at the file you are using on your computer which is probably under

/.oauth, especially if you are on a Mac. If not then look at the file path associated with GOOGLE_APPLICATION_CREDENTIALS environment variable to find the service account key file.

Part of the key number may be in the file name; otherwise, it will be inside the service account key file.

If a key has Expired then choose Add Key which will add one that is Active and download a json service account key file to your computer.

Move that json key file to where you reference your files. Some gcloud server connections automatically look under

/.oauth, but you can change that location with the GOOGLE_APPLICATION_CREDENTIALS environment variable.

If you have GOOGLE_APPLICATION_CREDENTIALS environment variable defined in your

/.bash_profile file then make sure to update the location there.

Wrap up

This post reviews JWT errors and specifically how to resolve the invalid_grant:Invalid JWT Signature error. For Invalid JWT Signature, check if your service account key has expired. Go to your APIs & Services to add a new key if it has.


How to verify a jwt ? #214


mridah commented Jun 27, 2018

Suppose I get a jwt string xxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxx

Now, how will I verify this jwt .

How will I convert this string back to an array to decode / verify it ? @bshaffer @mbleigh @ultrasaurus

The text was updated successfully, but these errors were encountered:

cottton commented Jun 28, 2018

mridah commented Aug 30, 2018

Thanks @cottton, that solved the problem 🙂

Also I would like to know one more thing: How to I revoke a jwt token ?

cottton commented Aug 30, 2018

Actually you cannot.

  • (auth-) server generates a JWT and handles it out to the client
  • client calls another service and provides the JWT
  • service validates the JWT and can trust the client

The JWT gives the client access as long

the JWT the «exp» claim (expiration Time) is valid

the public key is valid

an id in the JWT is not blacklisted

«exp» claim defines i.e. 5 min. So the client has a ticket for 5 min. After the 5 min the client needs to get a new access token (using f.e. a refresh token).

The service(s) gets updated and the public key changed. The JWT will not be valid anymore.

«Shared blacklist». F.e. the (auth-) server provides|distributes a black list. A service gets i.e. the user_id from the JWT and finds it on the shared blacklist. Access gets denied.
Instead of blacklisting the user you could also blacklist another id that identifies the JWT.

aamakerlsa commented Nov 4, 2018

I’m trying to verify tokens in a test environment (now that I am able to successfully create tokens). but I get this error after I manually change the secret / key for the decode attempt:

Fatal error: Uncaught Error: Class ‘Firebase\JWT\SignatureInvalidException’ not found in /My/Path/here/php-jwt-master/php-jwt-master-src/JWT.php:112 Stack trace: #0 /My/Path/here/php-jwt-master/testjwt2.php(44): Firebase\JWT\JWT::decode(‘eyJ0eXAiOiJKV1Q. ‘, ‘7772’, Array) #1

thrown in /My/Path/here//php-jwt-master/php-jwt-master-src/JWT.php on line 112

what do I need to do to NOT get the fatal error?

cottton commented Nov 5, 2018

Class ‘Firebase\JWT\SignatureInvalidException’ not found
Or for test manually use require_once .

aamakerlsa commented Nov 5, 2018

@cottton — solved it. I needed to add require for each of the exception classes:

require_once ‘php-jwt-master-src/BeforeValidException.php’;
require_once ‘php-jwt-master-src/ExpiredException.php’;
require_once ‘php-jwt-master-src/SignatureInvalidException.php’;
. in addition to the JWT.php require I already had

and in my try catch I had to use:

vedmant commented Dec 10, 2019

What if I need to decode token first and then only verify it agains a key, how can I do this? I’ll need to get «kid» value from the token before checking it signature, but JWT::decode() already requires key to use.

bshaffer commented Dec 10, 2019

To decode a string without verifying it against the public key, you can do this:

This is not supported directly in the library because of the possibility someone could use this unintentionally without verifying the signature.

cottton commented Dec 10, 2019

What if I need to decode token first and then only verify it agains a key, how can I do this? I’ll need to get «kid» value from the token before checking it signature, but JWT::decode() already requires key to use.

Had the same problem.
The kid *1

  • is in the first segment of the JWT
  • is json encoded
  • is part of the signature (included to created the signature)
    You actually should check if the signature is valid before using data from the JWT.
    BUT you cannot, if the system is using the kid from the header.
    Is SHOULD be save to extract the kid from the header
    and then check if the signature is valid.
Читайте также:  War thunder easy anti cheat не работает

I wrote a method to get the header.
You then can get the kid from the array and decode the JTW:


Create and Verify JWTs with Node

Authentication on the internet has evolved quite a bit over the years. There are many ways to do it, but what worked well enough in the 90s doesn’t quite cut it today. In this tutorial, I’ll briefly cover some older, simpler forms of authentication, then show you how a more modern and more secure approach. By the end of this post, you’ll be able to create and verify JWTs yourself in Node. I’ll also show you how you can leverage Okta to do it all for you behind the scenes.

Traditionally, the simplest way to do authorization is with a username and password. This is called Basic Authorization and is done by just sending username:password as an encoded string that can be decoded by anybody looking. You could think of that string as a “token”. The problem is, you’re sending your password with every request. You could also send your username and password a single time, and let the server create a session ID for you. The client would then send that ID along with every request instead of a username and password. This method works as well, but it can be a hassle for the client to store and maintain sessions, especially for large sets of users.

The third method for managing authorization is via JSON Web Tokens, or JWTs. JWTs have become the de facto standard over the last few years. A JWT makes a set of claims, (e.g. “I’m Abe Froman, the Sausage King of Chicago”) that can be verified. Like Basic Authorization, the claims can be read by anybody. Unlike Basic Auth, however, you wouldn’t be sharing your password with anyone listening in. Instead, it’s all about trust.

Trust, but Verify… Your JWTs

OK, maybe don’t believe everything you read on the internet. You might be wondering how someone can just make some claims and expect the server to believe them. When you make a claim using a JWT, it’s signed off by a server that has a secret key. The server reading the key can easily verify that the claim is valid, even without knowing the secret that was used. However, it would be nearly impossible for someone to modify the claims and make sure the signature was valid without having access to that secret key.

Why Use a JWT?

Using a JWT allows a server to offload authentication to a 3rd party they trust. As long as you trust the 3rd party, you can let them ensure that the user is who they say they are. That 3rd party will then create a JWT to be passed to your server, with whatever information is necessary. Typically this includes at least the user’s user id (standardly referred to as sub for “subject”), the “issuer” ( iss ) of the token, and the “expiration time” ( exp ). There are quite a few standardized claims, but you can really put any JSON you want in a claim. Just remember the more info you include, the longer the token will be.

Build a Simple Node App

To create and verify your own JWTs, you’ll first need to set up a Node server (well, you don’t have to, but that’s what I’ll be teaching you today). To get started, run the following commands to set up a new project:

Next, create a new file index.js that will contain a super simple node server. There are three endpoints in here, that are just stubbed with TODO s as notes for what to implement.

The /create endpoint will require basic authorization to log you in. If you were writing a real OAuth server, you would probably use something other than Basic Auth. You would also need to look up the user in a database and make sure they provided the right password. To keep things simple for the demo, I’ve just hard-coded a single username and password here, so we can focus on the JWT functionality.

The /verify endpoint takes a JWT as a parameter to be decoded.

You can now run the server by typing node_modules/.bin/nodemon . . This will start a server on port 3000 and will restart automatically as you make changes to your source code. You can access it by going to http://localhost:3000 in your browser. To hit the different endpoints, you’ll need to change the URL to http://localhost:3000/create or http://localhost:3000/verify/asdf . If you prefer to work in the command line, you can use curl to hit all those endpoints:

Create JSON Web Tokens in Your Node App

A JSON Web Token has three parts. The header, the payload, and the signature, separated by . s.

The header is a base64 encoded JSON object specifying which algorithm to use and the type of the token.

The payload is also a base64 encoded JSON object containing pretty much anything you want. Typically it will at least contain an expiration timestamp and some identifying information.

The signature hashes the header, the payload, and a secret key together using the algorithm specified in the header.

There are a number of tools out there to create JWTs for various languages. For Node, one simple one is njwt . To add it to your project, run

Читайте также:  По одной стороне машины не работают колонки

Now replace the res.send(‘TODO: create a JWT’) line in index.js with the following:

Feel free to mess around with the payload. With the setExpiration() function above, the token will expire in one minute, which will let you see what happens when it expires, without having to wait too long.

To test this out and get a token, log in via the /create endpoint. Again, you can go to your browser at http://localhost:3000/create , or use curl:

Verify JSON Web Tokens in Your Node App

Well, that looks a bit like gibberish. You can see there are two . s in the JWT, separating the header, payload, and signature, but it’s not human readable. The next step is to write something to decode that string into something that makes a little more legible.

Replace the line containing TODO: verify this JWT with the following:

In the route /verify/:token , the :token part tells express that you want to read that section of the URL in as a param, so you can get it on req.params.token . You can then use njwt to try to verify the token. If it fails, that could mean a number of things, like the token was malformed or it has expired.

Back on your website, or in curl, create another token using http://localhost:3000/create . Then copy and paste that into the URL so you have http://localhost:3000/verify/eyJhb. R8We4 . You should get something like the following:

If you wait a minute and try again, you’ll instead get jwt expired .

Add OIDC Middleware to Your Node App to Handle JWT Functionality

Well, that wasn’t so bad. But I sure glossed over a lot of details. That top-secret-phrase isn’t really very top secret. How do you make sure you have a secure one and it’s not easy to find? What about all the other JWT options? How do you actually store that in a browser? What’s the optimal expiration time for a token?

This is where Okta comes in to play. Rather than dealing with all this yourself, you can leverage Okta’s cloud service to handle it all for you. After a couple minutes of setup, you can stop thinking about how to make your app secure and just focus on what makes it unique.

Why Auth with Okta?

Okta is a cloud service that allows developers to create, edit, and securely store user accounts and user account data, and connect them with one or multiple applications. Our API enables you to:

  • Authenticate and authorize your users
  • Store data about your users
  • Perform password-based and social login
  • Secure your application with multi-factor authentication
  • And much more! Check out our product documentation

Create an Okta Server

You’re going to need to save some information to use in your app. Create a new file named .env . In it, enter your Okta organization URL.

You will also need a random string to use as an App Secret for sessions. You can generate this with the following commands:

Next, log in to your developer console, navigate to Applications, then click Add Application. Select Web, then click Next. Give your application a name, like “Fun with JWTs”. Change the Base URI to http://localhost:3000/ and the Login redirect URI to http://localhost:3000/implicit/callback , then click Done

Click Edit and add a Logout redirect URI of http://localhost:3000/ , then click Save.

The page you come to after creating an application has some more information you need to save to your .env file. Copy in the client ID and client secret.

Now back to the code. You’ll need to add Okta’s OIDC middleware to control authentication. It also relies on using sessions. You’ll need to use dotenv to read in variables from the .env file. To install the dependencies you’ll need, run this command:

At the very top of your index.js file, you’ll need to include dotenv . This will make it so that the secrets in your .env file can be read by your program. Add this line before anything else:

To get Okta set up securely, you’ll need to tell Express to use Okta’s OIDC middleware, which also requires sessions. Look for the line containing TODO: use Okta for auth in your index.js file, then enter the following just above it to initialize Okta with all your environment variables:

Now that you’re all set up, creating secure routes will be a breeze! To test it out, replace the remaining TODO: use Okta for auth line, with a route like this:

Now when you go to http://localhost:3000 , you’ll be redirected to a secure sign-in page. Since you’re probably still logged in to Okta from the admin panel, you may need to use a different browser or an incognito window to see the login screen as other visitors to your site would.

Once you sign in, you’ll get your hidden message!

Learn More about Node, JWTs, and Secure User Management

You can certainly do a lot more meaningful things than just printing Peekaboo! , but the key takeaway here is that after a quick setup, you can add authentication to any route in your Express server by adding a simple oidc.ensureAuthenticated() . Okta takes care of managing users, storing sessions, creating and verifying JWTs, so you don’t have to!

If you’d like to learn more about JWTs or Node, check out some of these other posts on the Okta developer blog:

If you have any questions about this post, please add a comment below. For more awesome content, follow @oktadev on Twitter, like us on Facebook, or subscribe to our YouTube channel.