394

If I get a JWT and I can decode the payload, how is that secure? Couldn't I just grab the token out of the header, decode and change the user information in the payload, and send it back with the same correct encoded secret?

I know they must be secure, but I just would really like to understand the technologies. What am I missing?

HDJEMAI
  • 7,766
  • 41
  • 60
  • 81
Z2VvZ3Vp
  • 5,098
  • 6
  • 18
  • 32

8 Answers8

494

JWTs can be either signed, encrypted or both. If a token is signed, but not encrypted, everyone can read its contents, but when you don't know the private key, you can't change it. Otherwise, the receiver will notice that the signature won't match anymore.

Answer to your comment: I'm not sure if I understand your comment the right way. Just to be sure: do you know and understand digital signatures? I'll just briefly explain one variant (HMAC, which is symmetrical, but there are many others).

Let's assume Alice wants to send a JWT to Bob. They both know some shared secret. Mallory doesn't know that secret, but wants to interfere and change the JWT. To prevent that, Alice calculates Hash(payload + secret) and appends this as signature.

When receiving the message, Bob can also calculate Hash(payload + secret) to check whether the signature matches. If however, Mallory changes something in the content, she isn't able to calculate the matching signature (which would be Hash(newContent + secret)). She doesn't know the secret and has no way of finding it out. This means if she changes something, the signature won't match anymore, and Bob will simply not accept the JWT anymore.

Let's suppose, I send another person the message {"id":1} and sign it with Hash(content + secret). (+ is just concatenation here). I use the SHA256 Hash function, and the signature I get is: 330e7b0775561c6e95797d4dd306a150046e239986f0a1373230fda0235bda8c. Now it's your turn: play the role of Mallory and try to sign the message {"id":2}. You can't because you don't know which secret I used. If I suppose that the recipient knows the secret, he CAN calculate the signature of any message and check if it's correct.

HDJEMAI
  • 7,766
  • 41
  • 60
  • 81
Misch
  • 8,600
  • 4
  • 33
  • 48
  • 11
    So the signature is changed when the payload is changed? I was under the impression the token was in the format [header].[payload].[signature] is the signature calculated by combination of the payload and secret? If that was the case, wouldn't a payload with a different id be the same for that secret? Like if the data was { id:1 } and that is used to calculate the signature part of the token with the secret, wouldn't that mean that { id:2 } would be valid for user 2, and so user 1 could change id to 2 and the token would be the same? – Z2VvZ3Vp Dec 04 '14 at 21:22
  • 1
    For instance I'm going here and changing the data in the payload and it says signature valid unless i enter invalid characters: http://jwt.io/ http://grab.by/CNGS – Z2VvZ3Vp Dec 04 '14 at 21:23
  • @PixMach Edited the answer – Misch Dec 04 '14 at 21:32
  • Thanks, but it seems like if Mallory changes the hash by changing the id in the payload, Hash(newContent+secret) would be valid. So does this mean I have to send the user with the request to match against the JWT? I am wondering if I can't rely on the payload to tell me who is doing the request. – Z2VvZ3Vp Dec 05 '14 at 00:14
  • 15
    Oh I understand now. I don't know why I was missing the idea that the secret hash would not be correct when you changed the payload because the secret hash would have to be recalculated. For some reason I was still thinking that it was independent. That last bit really drilled it home for me. Thanks for walking me through it. – Z2VvZ3Vp Dec 05 '14 at 16:07
  • 41
    I have a related question. What's preventing someone from impersonating Alice with the copied JWT? – Morrowless Aug 23 '16 at 08:03
  • 32
    If someone has the JWT they can impersonate Alice. So you need to be careful how you store and send it. You should also set an expiry for it in the payload. That way if someone steals the JWT they have a limited timeframe to use it. Have a look at https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage – Geraint Anderson Aug 26 '16 at 14:35
  • 3
    @Morrowless I've ran into the issue of users "sharing" tokens. What we did to improve security was to use the user's IP address as part of the decrypting process. Because this happened in the back-end; a user could share a token with another but get denied not knowing why. At the same time we destroyed/invalidated the shared token so both users would have to sign in again and get a new token. Of course, this is not perfect because you could still get away with it if you were connected to the same network. What I'd love to see is a browser enforced session ID passed via the headers. – calcazar Dec 20 '16 at 19:43
  • 1
    if someone with copied jwt can impersonate alice, then what is the use of jwt then , is not is better to use a simple encrypted key that is different for every user and generated at the time of signup and saved in database.atleast to save development time. – Dragon Feb 19 '17 at 11:49
  • 1
    The assumption made is that secret is not known. Say I know the secret and hash method you are using, then I can pretend to be any user in the system. How do you solve this problem? – Alex Jan 13 '18 at 08:39
  • PKI with RSA may be used to make tokens more secure. Thus server will have Public Key of user and user will have Private Key stored in Cryptographic Device like HSM or USB Token or Smart Card, which never comes out of such device and has no chance of compromise. Use RS256 to sign JWT then. – Bharat Vasant May 02 '19 at 00:24
  • In this example, is Mallory able to verify the integrity of the JWT and if so, how can she do it without the secret? – rangfu Jan 21 '21 at 08:20
  • 1
    @rangfu No, not in this example. Using HMAC (symmatrical cryptography) was only to illustrate the example. If you need a third party to be able to verify the integrity of the JWT, you can use an asymmetrical signing algorithm. – Misch Jan 28 '21 at 17:53
174

You can go to jwt.io, paste your token and read the contents. This is jarring for a lot of people initially.

The short answer is that JWT doesn't concern itself with encryption. It cares about validation. That is to say, it can always get the answer for "Have the contents of this token been manipulated"? This means user manipulation of the JWT token is futile because the server will know and disregard the token. The server adds a signature based on the payload when issuing a token to the client. Later on it verifies the payload and matching signature.

The logical question is what is the motivation for not concerning itself with encrypted contents?

  1. The simplest reason is because it assumes this is a solved problem for the most part. If dealing with a client like the web browser for example, you can store the JWT tokens in a cookie that is secure (is not transmitted via HTTP, only via HTTPS) and httpOnly (can't be read by Javascript) and talks to the server over an encrypted channel (HTTPS). Once you know you have a secure channel between the server and client you can securely exchange JWT or whatever else you want.

  2. This keeps thing simple. A simple implementation makes adoption easier but it also lets each layer do what it does best (let HTTPS handle encryption).

  3. JWT isn't meant to store sensitive data. Once the server receives the JWT token and validates it, it is free to lookup the user ID in its own database for additional information for that user (like permissions, postal address, etc). This keeps JWT small in size and avoids inadvertent information leakage because everyone knows not to keep sensitive data in JWT.

It's not too different from how cookies themselves work. Cookies often contain unencrypted payloads. If you are using HTTPS then everything is good. If you aren't then it's advisable to encrypt sensitive cookies themselves. Not doing so will mean that a man-in-the-middle attack is possible--a proxy server or ISP reads the cookies and then replays them later on pretending to be you. For similar reasons, JWT should always be exchanged over a secure layer like HTTPS.

gunr2171
  • 10,315
  • 25
  • 52
  • 75
aleemb
  • 28,346
  • 17
  • 92
  • 111
  • 8
    Mind it! JWT should always be exchanged over a secure layer like HTTPS – codemirror May 30 '19 at 10:25
  • But if JWT is only secure over HTTPS, why not just send the payload? POST -> username, password. It is still encrypted right? – GeekPeek Dec 09 '19 at 07:56
  • @GeekPeek for that you should read up on JWT basics but Session Auth like you mention is often all you need. JWT offers some other benefits but makes some tradeoffs https://www.webskeleton.com/webdev/2019/10/22/JWT-Primer-and-Should-You-Use-It.html – aleemb Jan 09 '20 at 16:08
  • 2
    You just read what is in my mind, In fact, as I am newbie I was surpised that jwt.io can read my payload so what the signature is doing exactelly ? now my biggest question What Happens If Your JWT Is Stolen?!!! – da45 Jul 17 '20 at 18:40
  • @aleemb, how is it secure if the hacker doesn't tweak jwt but uses the same jwt instead to make and retrieve some important data? Won't server would believe that it's a genuine request? Or is there something I am missing? – infinite Dec 21 '20 at 08:51
98

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Arthur Costa
  • 776
  • 11
  • 24
Lord
  • 2,830
  • 10
  • 17
  • 1
    hi @Lord, this is awsome! I dont know why it is with so less up votes! – ani0904071 Jun 24 '20 at 18:40
  • 1
    hi @ani0904071, In the below link you will find an example with node.js, I hope it will help too. https://stackoverflow.com/questions/31309759/what-is-secret-key-for-jwt-based-authentication-and-how-to-generate-it/62095056#62095056 – Lord Jun 25 '20 at 09:21
  • 3
    This answer is great! In very simplified form, if the JWT was "2.5.9" (header=2, payload=5, signature=9) then tampering with it and changing the data to 6 wouldn't work. Let's say the servers secret is multiplying header*payload and subtracting 1. The "test signature" would be 2*6-1=11. But the JWT's signature is 9, so the server knows that something has been tampered with. It's easy once understood, but for some reason many articles leave out the low-level stuff, which makes it seem more magical and complicated than it really is. – Magnus W Jul 07 '20 at 07:52
  • Thanks, now I understand it. So simple, yet so hard to grasp. Now it seems trivial. – Jesus Oct 15 '20 at 19:28
  • AWESOME EXPLANATION! – Bilaal Abdel Hassan Nov 08 '20 at 20:52
  • @Lord, how is it secure if the hacker doesn't tweak jwt but uses the same jwt instead to make and retrieve some important data? Won't server would believe that it's a genuine request? Or is there something I am missing? – infinite Dec 21 '20 at 08:50
  • @infinite I believe this keywords will help you, JWT , Auth, PrivateRoute, AdminRoute – Lord Dec 21 '20 at 09:05
  • @Lord, doesn't seem to be helping much. – infinite Dec 21 '20 at 10:38
  • The problem is not what happens when one modifies the JWT. The problem is what happens when person B can access a JWT of person A (eg they sit next to each other, person A goes to toilet, person B opens dev tools in person A's chrome and copy pastes the JWT from local storage and sends it to his pc), and uses this to issue calls in the API. How is it possible to tell that the request coming from person's B pc (but is actually issued to person A) is invalid? – Thanasis Ioannidis Jan 27 '21 at 10:47
  • @ThanasisIoannidis this reminds me of Session Hijacking, but somehow different, since Session Hijacking's primary manner of attack would be sniffing.. Now, for your case, Person B would still be, somehow, 'Hijacking' Person's A JWT Token.. In a sniffing case, this would be resolved by using HTTPS, now, in your case, there's not much we can do. It's an infosec concern to actually educate the employees to not let their PCs unlocked when not at the desk. – Matheus Cirillo Jan 30 '21 at 13:27
25

The contents in a json web token (JWT) are not inherently secure, but there is a built-in feature for verifying token authenticity. A JWT is three hashes separated by periods. The third is the signature. In a public/private key system, the issuer signs the token signature with a private key which can only be verified by its corresponding public key.

It is important to understand the distinction between issuer and verifier. The recipient of the token is responsible for verifying it.

There are two critical steps in using JWT securely in a web application: 1) send them over an encrypted channel, and 2) verify the signature immediately upon receiving it. The asymmetric nature of public key cryptography makes JWT signature verification possible. A public key verifies a JWT was signed by its matching private key. No other combination of keys can do this verification, thus preventing impersonation attempts. Follow these two steps and we can guarantee with mathematical certainty the authenticity of a JWT.

More reading: How does a public key verify a signature?

Community
  • 1
  • 1
ThisClark
  • 12,145
  • 9
  • 61
  • 89
3

Ref - JWT Structure and Security

It is important to note that JWT are used for authorization and not authentication. So a JWT will be created for you only after you have been authenticated by the server by may be specifying the credentials. Once JWT has been created for all future interactions with server JWT can be used. So JWT tells that server that this user has been authenticated, let him access the particular resource if he has the role.
Information in the payload of the JWT is visible to everyone. There can be a "Man in the Middle" attack and the contents of the JWT can be changed. So we should not pass any sensitive information like passwords in the payload. We can encrypt the payload data if we want to make it more secure. If Payload is tampered with server will recognize it.
So suppose a user has been authenticated and provided with a JWT. Generated JWT has a claim specifying role of Admin. Also the Signature is generated with

enter image description here

This JWT is now tampered with and suppose the role is changed to Super Admin
Then when the server receives this token it will again generate the signature using the secret key(which only the server has) and the payload. It will not match the signature in the JWT. So the server will know that the JWT has been tampered with.

Batman Rises
  • 171
  • 1
  • 3
3

I would explain this with an example.

Say I borrowed $10 from you, then I gave you an IOU with my signature on it. I will pay you back whenever you or someone else bring this IOU back to me, I will check the signature to make sure that is mine.

I can't make sure you don't show the content of this IOU to anyone or even give it to a third person, all I care is that this IOU is signed by me, when someone shows this IOU to me and ask me to pay it.

The way how JWT works is quite the same, the server can only make sure that the token received was issued by itself.

You need other measures to make it secure, like encryption in transfer with HTTPS, making sure that the local storage storing the token is secured, setting up origins.

Sheng Zhuang
  • 377
  • 1
  • 7
0

Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.

Hide the privateKey in a secure location in your server and never tell anyone the privateKey.

sdfdsf sdf
  • 223
  • 2
  • 10
  • 3
    JWTs are not always encrypted. They can be signed, encrypted, signed then encrypted, or encrypted then signed. – csauve Jan 21 '19 at 18:23
-2

I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt

Reference link: https://www.npmjs.com/package/node-webtokens

jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
  jwt.parse(token).verify(pwd, (error, parsedToken) => {
    // other statements
  });
});

This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.

A simple example which I have created: https://github.com/hansiemithun/jwe-example

Mithun Shreevatsa
  • 2,689
  • 7
  • 34
  • 71