ChatGPT解决这个技术问题 Extra ChatGPT

If you can decode JWT, how are they secure?

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?

md5('original messaged' + secret) != md5('changed message' + secret) thus if someone changes the message you can detect it
@YashKumarVerma yes, it's just to demonstrate the gist of it since everyone knows md5.
@user1955934 it is base64 encoded, NOT encrypted. You can simply decode it with any base64 decoder.
so the client will need to send both the hash and the jwt token? and later on in the server side they will try to hash the jwt token using secret and compare with the hash?
A server should never trust the client to handle and return sensible data. Only hashes that the server can then internally use to retrieve the actual data, most likely from a database.

H
HDJEMAI

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.


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?
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.
I have a related question. What's preventing someone from impersonating Alice with the copied JWT?
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 stormpath.com/blog/…
@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.
g
gunr2171

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?

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


Mind it! JWT should always be exchanged over a secure layer like HTTPS
But if JWT is only secure over HTTPS, why not just send the payload? POST -> username, password. It is still encrypted right?
@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 webskeleton.com/webdev/2019/10/22/…
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?!!!
Sensitive information like password, credit card details, etc. MUST not be encoded in JWT
A
Arthur Costa

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.

https://i.stack.imgur.com/UXiHK.png

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.

https://i.stack.imgur.com/tTxqp.png

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.

https://i.stack.imgur.com/0FpIC.png

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.

https://i.stack.imgur.com/bOHqZ.png

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.

https://i.stack.imgur.com/b2dzI.png

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.


hi @Lord, this is awsome! I dont know why it is with so less up votes!
hi @ani0904071, In the below link you will find an example with node.js, I hope it will help too. stackoverflow.com/questions/31309759/…
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.
Thanks, now I understand it. So simple, yet so hard to grasp. Now it seems trivial.
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?
T
ThisClark

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?


S
Sheng Zhuang

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.


Perfect analogy!
> encryption in transfer with HTTPS, making sure that the local storage storing the token is secured, setting up origins < Please explain in more detail how to do it?
B
Batman Rises

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

https://i.stack.imgur.com/IIsJ3.png

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.


+1 for emphasizing that JWTs are NOT for authn, but for authz. I don't know why so many sites and people say they are for authn. JWTs do NOT prove the identity of the requestor at ALL. I guess everyone is trying to make the inference that a requestor would only have a JWT AFTER they've authenticated to your service, but that isn't necessarily true.
Just curious.. @Ungeheuer Why do you think JWT not considered as authentication token? It has the payload where the user-info is present. The header, payload and secret key are used to “validate" the original signature (which was initially generated by the authentication server) which means if any change in payload then user is said to be not original user and hence not authentic. Isn't it simplifies the authn process i.e. with token we can authenticate the user for every request without going to authentication server again and then allow the access to resource based on user role.
cloud.google.com/api-gateway/docs/authenticating-users-jwt explains other way to what this answer explains.
s
sdfdsf sdf

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.


JWTs are not always encrypted. They can be signed, encrypted, signed then encrypted, or encrypted then signed.