I want to add authentication to my application using jwt tokens.
Every time I send request to the server I attach the token that my server created.
I wounding, is this secure way to send the token in the headers? what if somebody access to my computer and check my network in devtools tab and see my token, he can mimic the request with the token and take control the user data.
Is this common scenario? and the ways for stole and hacking jwt tokens?
Yes its common to attach the token to the header. It looks something like this:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
Sure somebody could go into your computer and check the token. But usually your computer has some kind of authentication aswell to log in. Same with phone, almost everybody has some kind of password.
A good way to store tokens are httpOnly cookies. With this flag javascript cannot read the cookie on the client side. It makes XSS attacks harder to get the token.
The problem about JWT are that they have a expire date and they are valid till they reach the date. Lets say you log in into a webpage, and get some token. Now somebody steal your token. You log off and erase the token form your device.
The problem is now that the token is stolen and still valid so the attacker can use it.
At this point the attaker is technically you because he has the token with the saved data in it.
What you can do here is to create a blacklist. If you log out you put your token into the blacklist. Whenever somebody try to access something that requires a token, you first check if that token is inside the blacklist, if it is you reject the request.
For a blacklist i would recommend a cache like redis for fast access.
The token is a short-lived key. Anyone with access to the token has access to whatever that key unlocks. It feels insecure, but this is a fundamental property of using tokens. You use HTTPS to encrypt the data so that it can't be read along the way, but there's always going to be ways for people to obtain the token.
There are often trade offs between ease of access and security. People have accepted the risks associated with using tokens for authentication. To be clear, any authentication method that stores a key has this problem; the only real alternative is to ask for the password for every request, but ain't nobody got time for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With