Is payload tampering possible when making request to resource server with JWT? - jwt

As we know the JWT is signed with secret key so the token itself can not be tampered but the payload we send to resource server with JWT can be plain text/json/xml/query string so how can we protect payload from tampering?

The signature is exactly what prevents the payload from being tampered. The payload cannot be modified without invalidating the signature.
Let me also clarify that JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT is a generic name for the following types of token:
JSON Web Signature (JWS): The payload is encoded and signed so the integrity of the claims can be verified.
JSON Web Encryption (JWE): They payload is encrypted so the claims are hidden from other parties.
If you intend to prevent the payload from being tampered, then use JWS. If you want to hide the payload from other parties, then use JWE.

tl;dr To keep your payload (and token in general) safe all you need to do is use a strong secret and signing algorithm and verify the signature before trusting the contents.
JWT is signed with secret key, but the payload can be plain text/json/xml/query
You seem to be confused on what a JWT is. There is no separate JWT and payload, one is part of the other. JWT consists of Header, Payload and Signature. Signature is created over both - the header and payload parts and additionally your secret key. This means that if either piece is tampered with the signature can not be verified.
From JWT introduction:
Do note that for signed tokens this information [header and payload], though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.
To see for yourself you can use JWT debugger. When you change the decoded header or payload their base64 values change and therefore the signature changes with them. If you were to copy-paste the old signature value into new JWT it will show invalid signature error.

Unfortunately, there is no standard way to ensure that the request body has not been tampered during the transport using http headers.
AFAIK and among all the authentication schemes listed by the IANA, none of them have such feature.
However if your project is limited to a few number of clients or if you provide a detailed documentation, you can implement your own request signature mechanism.
I recommend you to read more about the following initiatives. Theses ones could help you in that implementation:
AWS Signature Version 4: certainly the most interesting resource. It also allows POST (maybe PUT and PATCH) requests to be signed
Hawk: same as above. Not widely used though.
OAuth 2.0 Message Authentication Code (MAC) Tokens. This one is abandonned and do not ensure the body has not been modified.

JWT by itself is not tamper proof. To make it secure, it must be transformed with these 2 steps:
Sign with Sender's private key
Encrypt with Receiver's public key
Signing with sender's private key ensures that any unauthorized modification of token can be detected.
Encrypting with Receiver's public key will ensure that the token achieves secrecy and only the intended receiver can see the token content.
JWT signed by Sender is called JWS.
Encrypted JWS is called JWE.
More information:
https://dzone.com/articles/securing-spring-boot-microservices-with-json-web-t

Related

Is it possible to edit the JWT token? [duplicate]

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?
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.
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.
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.
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.
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.
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.
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.
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.
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?
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.
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
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.
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.
I am not a cryptography specialist and hence (I hope) my answer can help somebody who is neither.
There are two possible ways of using cryptography in programming:
Signing / verifying
Encryption / decryption
We use Signing when we want to ensure that data comes from a trusted source.
We use Encryption when we want to protect the data.
Signing / verifying uses asymmetrical algorithms i.e. we sign with one key (private) and the data receiver uses the other (public) key to verify.
A symmetric algorithm uses the same key to encrypt and decrypt data.
The encryption can be done using both symmetric and asymmetric algorithms.
relatively simple article on subject
The above is common knowledge below is my opinion.
When JWT is used for simple client-to-server identification there is no need for signing or asymmetric encryption. JWT can be encrypted with AES which is fast and supersecure. If the server can decrypt it, it means the server is the one who encrypted it.
Summary: non-encrypted JWT is not secure. Symmetric encryption can be used instead of signing in case no third party is involved.

What is a secret key in JWT

I am unable to clearly grasp how JWT works, esp. the signature part.
Once a client submits correct username and password, the authentication server creates a JWT token consisting of header, payload/claims and signature.
Question 1 - Is signature some secret key (not the user's password) which only the authentication server knows (sort of a private key of the server)?
Question 2 - Say I am using a separate application server and authentication server, on receiving JWT from client, would the application server send the JWT to authentication server to get it validated? I suppose the application server cannot validate a JWT token as it doesn't know the secret key used to sign the header and payload.
Question 3 - I took the following JWT and pasted it on jwt.io. I see the message Signature Verified. How does jwt.io know that the signature is correct as it doesn't know the secret key.
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxLS9tSjVsVTNYc09QWCt2VitpaGZRMWlCUDVjUTROQm1hNDluOE9rS1FFSnEzTDFNOTl2VW9iQ1ZLUHVYMmdlWWhYaHJQM0t3bHY4SE1RaHNGdnFjbllIeGxGSHM9IiwiaXNzIjoicGxheS1zaWxob3VldHRlIiwiZXhwIjoxNTI2MjgxMDU1LCJpYXQiOjE1MjYyMzc4NTUsImp0aSI6IjhmOGM3YTVmYWRkNTE5MjUxNzQ5NGE4N2Q1ODcxZjJjZGUxZDkzMDdkOTY1MThjNjg2NzExOTc1YjU3M2I5NDBlZWU2NGY0NDUwYzcxODI3NGZmNzU1MmE2Y2JlNTVmZmZhMWI1ZjA3ZWZlOWVkNTE0Y2Y4YTViOTZlM2ExYjI0ODRmYTI5NjZiYjA0ODlmODIwZjMyMzM5YWVhNjM3NWRkZmU4ZDE4N2E2NzBjMzg0ODgwZGIyMzQ1ZTFkMzRkYWNjZmY2MTdkMDY1NzU3YmEwZTQzNDg4YWFhZmZmNDNjYWZlZGY0OTFlODU1YTA0NWM0NmJjNDY4NGYzODlmY2YifQ.GwN6TSNd426xpc3Y02eRXHbrmSr_61MMBqrmx66Ofqs
Question 1 - Is signature some secret key (not the user's password) which only the authentication server knows (sort of a private key of the server)?
No, the electronic signature is a mathematical computation applied to the payload of the JWT using a secret key. The purpose is to ensure that the message has not been altered and to recognize the signer to validate the JWT
Question 2 - Say I am using a separate application server and authentication server, on receiving JWT from client, would the application server send the JWT to authentication server to get it validated? I suppose the application server cannot validate a JWT token as it doesn't know the secret key used to sign the header and payload.
Not necessarily. If a symmetric key (HMAC) is used, the signature and verification key is the same. In that case the Authorization server must know the secret key or send the token to verify. However, if an asymmetric key (RSA, ECDSA) is used, the signature key is different from the verification key. The authorization server can have a copy of the public key safely
Question 3 - I took the following JWT and pasted it on jwt.io. I see the message Signature Verified. How does jwt.io know that the signature is correct as it doesn't know the secret key.
jwt.io or anyone who wants to verify the token needs the secret key. Note that if you copy-and-paste the token in jwt.io, the signature is not verified, but if you change the secret key, the editor changes automatically the signature creating a new token at the time
Signature is just hashing using secret key generated by authentication server, using algorithm specified in header, a combination of your header, payload, and secret
Only the authentication and/or application server knows that secret. JWT is encoded and signed, but not encrypted. to understand difference between Sign/Hash and Encryption, check this
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
Signature just verifies or validates whether the message was already hashed before using the same kind of algorithm specified in the header with the secret that is known only by server.
To understand how it works in authenitcation, here is a flow:
User sign in, you send user/pass to server in an encrypted way over https
Server validates username/pass from your db
Server generates a JWT and send it back to you, The signature is used here to verify the message wasn't changed along the way.
Server saves the JWT somewhere in a session store.
Later, user requests a server (send JWT everytime it needs something from the server)
Server validates it using same type of hash algorithm that is in the header and secret stored in there.
Server checks whether it is already there in session store.
Servers authorizes and grants you for the request.
I would recommend you read this article that is more descriptive to better understand how it works.

PayPal id_token verification

I'm implementing "Log In with PayPal" functionality. Should be fairly simple, but unfortunately PayPal lacks documentation (only some basic things are described).
I get authorization_code using "Log In with PayPal" widget. Than I make a request to https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice and get JSON with access_token, refresh_token and id_token. I want to get unique user identifier, so I decode id_token, but I'm not able to verify signature of my id_token. Id_token header contains {"alg": "HS256", "typ": "JWT"}.
What secret should I use? Tried my app's secret (same that I use to access tokenservice), but it didn't work (using https://jwt.io/ debugger).
PayPal is not OpenID connect compliant. This answer explains the reasons.
PayPal expose a configuration endpoint - https://www.paypalobjects.com/.well-known/openid-configuration.It only support HS256 and does not support or mention about RS256. This could be due to a proprietary validation for ID token. For example a id token used as a bearer token.
Alternative solution would be to invoke userinfo endpoint as described by document. This endpoint can be invoked using access token and document says it would return the user_id
user_id - identifier for the end-user at the issuer.
Although it seems that user_id found in the userinfo is different from sub that could be extracted from id_token.
How to find public keys if signing algorithm is RS256
ID token is a JWT. As you have found out, it contains a JWS signature which acts as a MAC.
This signature is a signed using a private key. The receiver of the id token can validate the token using the public key. To find the public key, openid conenct specify a discovery document. You can read more about this from the specification
In the discovery document, you get a special endpoint to infer the configuration .well-known/openid-configuration. And one of the must have metadata of the configuration response is jwk_url
jwks_uri
REQUIRED. URL of the OP's JSON Web Key Set [JWK] document. This
contains the signing key(s) the RP uses to validate signatures from
the OP. The JWK Set MAY also contain the Server's encryption key(s),
which are used by RPs to encrypt requests to the Server. When both
signing and encryption keys are made available, a use (Key Use)
parameter value is REQUIRED for all keys in the referenced JWK Set to
indicate each key's intended usage. Although some algorithms allow the
same key to be used for both signatures and encryption, doing so is
NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be
used to provide X.509 representations of keys provided. When used, the
bare key values MUST still be present and MUST match those in the
certificate.

Do we need to validate JSON Web Token at client/consumer?

I am studying a bit about JSON Web Token. I understood that header+claims get signed by a secret key and the encoded result gets concatenated to "header.claims.signature" and finally sent back to client.
I have some basic doubts:
Do we need to validate the token at client/consumer (once it receives from server, for sake of authenticity)? Is it a standard at all or not necessary? Any example for reference on this?
If the client needs to validate the token, I guess it has to know the secret key to decrypt/decode. Is there any other way to ask client validate on its own without sharing server's secret key?
If client knows the secret key, I guess it can create its own token too. If such is the case, do the server need to accept such tokens (or is application/business dependent?)
Do we need to validate the token at client/consumer
On client side you usually don't validate the token. Treat it just as an opaque token. Keep it safe and use it when making requests to the server.
If the client needs to validate the token, I guess it has to know the secret key to decrypt/decode.
As mentioned above, the client doesn't need to validate the token.
In any cases in which the authentication server (the instance that authenticates the user and issues the token) and the resource server (the instance that owns a proteceted resource and requires a token for authorization) are not the same, signing and validation of the token is usually done with asymmetric algorithms like RS256 in which the private key is used to sign the token and only known by the authentication server, and the public key is used to verify the signature.
If client knows the secret key, I guess it can create its own token too. If such is the case, do the server need to accept such tokens (or is application/business dependent?)
That's why a client should not know the secret key.
When symmetric key algorithms (e.g. HS256), in which the same key is used to sign and verify a signature are used, you can't allow the client to know the key, as it could be abused to create a fake token. Then JWT would be pointless. For asymmetric keys, there's no risk if the client knows the public key.

Is the JOSE Header a mandatory part of a JWT token

I am looking at adding JWT ability to a token generation system which is currently supporting SAML with our own signature and custom algorithm. In this case, should we always have the JOSE Header for the token or can we generate just the JWT with the Claims alone.
A JWT as sent on the wire in its compact serialized representation must always include a header, but if you don't sign the JWT, that header can be set to the base64encoded value of {"alg":"none"}.
However if you want to send it between two systems that you control and implement, you could only sent the payload JSON object, i.e. the JWT Claims Set. Of course you would then not be able to parse it using a JWT library, but you'd treat it like any other JSON object with a plain JSON parser.