You can generate your own JWT token like you state, but it will not be accepted by the backend.
To see, why, take this example token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
If you look closely, you see 2 times a '.' (dot).
Everything before the first dot is the header, and decodes in this example as:
{
"alg": "HS256",
"typ": "JWT"
}
The part between the first and second dot is the payload which holds your claims and decodes in this example as:
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
Then finally, everything after the second dot is the verification signature.
So this part:
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
This signature is computed based on the information in the header and the payload. Furthermore, the encryption algorithm used is provided in the header: HMAC SHA256
in this example.
To run this encryption algorithm on the header and payload data using HMAC SHA256
you need a key
.
This key
is secret and only known by the server granting you access to its recources.
So this server can generate the JWT token having the header and payload and - using its secret key - generate the verification signature. Then this JWT token is send to you. When you send the JWT token back to the server (because you want to access a resource), the server can check the verification signature using its key
to check if the signature is valid. If so, it will accept the token, and grand you access.
You probably already feel it comming. Now suppose you generate your own fake JWT token like you describe. You cannot determine the verification signature yourself as you don't have the secret key
. If you just put any signature, the server will recognise the invalid signature when it verifies it with the true key
and reject your token. That is why you cannot generate your own fake JWT toke that allows you to fake authenticate or impersonate.
TLDR:
One more thing, like others have pointed out. When the server sends you a valid JWT token, it can be stolen! If someone obtains this valid JWT token, than that someone can impersonate you and get access to the resources on your behaf. They cannot change the token or generate their own, but they can use the stolen one as is.
That is why, just like normal passwords, a JWT token should be send over an encrypted communication channel like HTTPS so only you and the server can see the token.
Also, your JWT token should have an expiration time. In case it does get stolen, the attacker has access only for limited time which hopefully reduces the damage.
Hope this clarify things a bit.