does data in jsonwebtoken are un rewritable - node.js

I'm using jsonwebtoken on my node js server and inside the jsonwebtoken i store the role of the user.
So everytime he do a request i just have to check if the required role is given in the token. But do people can change this role ?
I know everyone can see it but i guess no one can change it without my secret, right ?
Off course i m always checking the jsonwebtoken is correctly signed.
Do you think this method seems good ?
Sorry, english is not my main language

if you change the jwt data and then hash it with a different signature then you server will know its a fake token.
also make sure you use https so your tokens wont be available to sniffs.
if you store your token in a cookie make sure you put your cookie with http-only to prevent cookie highjack
also i recommend you to use csrf token to prevent csrf attacks

I guess you store the jwt in a Cookie or in LocalStorage on the client side.
So ofc, the user can delete or alter the cookie but he can't read it without your secret.
So if he tries to update the token, it will probably become corrupted and unreadable from your server side.
If the token is corrupted you'll probably want to log-out the user and redirect him to the login page.

Related

Difference between Token based and Session based Authentication

So, I've implemented some form of auth on my API, I'm not sure which kind it classifies as.
What my app does is, it generates a token once a user signs up/logs in and then before every endpoint call, I have a middleware function that checks if a token exists, then decrypts it, and if it's correct then its stores the user info in req.user. I then use the user info in req.user for other stuff later.
Does this classify as Token based auth?
I looked up online and read that instead of storing the token as a cookie on the client side, if I store the user info on the server side as session and a sessionid as a cookie on the client side, it classifies as Session based auth.
Thus clearly, my app has Token based auth right?
(I'm sorry if I'm seeking clarification for very basic stuff, I'm very much a beginner)
Yes you have implemented the token based authentication in your scenario, session based is totally different thing on that approach you need to store session in your backend to track is client valid or not, but in token based you don't need to store sessions but you will have two tokens as ACCESS TOKEN and REFRESH TOKEN and need to store refresh token in database incase of future regeneration of access token that's how token based authentication works!
You write that you "check if a token exists" and I assume this means that you look it up on a database. This is rather similar to an express-session, where the cookie contains a token and the session is also looked up on the database. The difference could be that you transport your token not in a cookie but in a request header (you don't say which technique you use).
However, one important aspect of token-based authorization is that the token need not be looked up on a database, but can be validated entirely in memory by verifying a signature. This is quicker and consumes fewer resources. Especially if your server receives many (malicious) requests with invalid tokens, it can detect and reject them without putting load on the database. See also the answer to Some questions about refresh tokens.
You could combine this with a session-based approach if the session ID also contains a signature and this is validated before the session is looked up on the database.
Read more about signed tokens and signature validation under the jwt tag.

Is Safe JWT Store in Req. Session?

i have a question about MERN Stack (Mysql,Express,React,Node). I confused about storing Jwt token (in Cookies,Localstorage or as session in request).
What iam asking is Is Safe Storing JWT On Request Session ?
Can someone explain how to store token in Single Page App ?
Thanks Anyway ...
When we do a successful login we get an access token. In this case, it is a JWT token. When we get this we need to keep it somewhere to use it for the future use of the user. We normally store that in LocalStorage. You can find more info about LocalStorage here. We also can use SessioStorage, Cookies as well. But Cookies only can contain 4KB of data and SessionStorage will go away when the browser is closed. That is the reason for me to go with LocalStorage. But you can choose it depending on your application requirement.
When sending a request with a token, I use the Authorization header.
It's safe to store JWT cookie at the client and even more in this day and age it necessary for scalability.
What should you use?
Session - This is the "old" way of doing things and no in use anymore. The session saves a state on the API server and that is a bad thing for scaling.
Localstorage - A good choice for mobile and web applications. The idea here is that you as the client developer are responsible for keeping track of JWT (save it on login, remove it on logout)
JWT-Cookie - is the best for ONLY web application. It's the same idea of Localstorage but now the server is responsible for setting and removing the JWT from the client using the Set-Cookie header.
Note: You can implement both Localstorage and JWT-Cookie side by side.

Where can we store the JWT token securely?

1. User will do the login UserName and password.
2. If the login success then server will return JWT.
3. Now we will store the token.
4. Now for every request we will send the JWT Token for authentication on server.
My question is that Where can we store the JWT token because Local storage,Session,Cookies is not safe.
"Only the server should know the "secret" that is used to generate the JWT. If someone modifies the data contained in the JWT, the server will fail to decode it. So the server can trust any JWT that it can decode."
You don't need to store JWT token where someone can't find. And if you think if hackers get token of someone, there is a expiration date option for this.
Check this: How safe is JWT?
httpOnly cookie
It's a special kind of cookie that’s only sent in HTTP requests to the server, and it’s never accessible (both for reading or writing) from JavaScript running in the browser.
Check this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
You can use this Package to make your life easier if you want:
https://www.npmjs.com/package/react-cookie

jwt token how to ensure the payload is updated when database change

I have a question regarding the concept of JWT token type of authentication.
So suppose I sign a jwt token after user logged in, the token payload contains the username and userRole. I then return the token to the user and store in user's localStorage.
Now, if i change the userrole in database, i.e. from normalUser to AdminUser, how can I then ensure the payload on user's localStorage also change?
I have an issue when if the user is an admin user, when he signs in, a jwt is stored in his localStorage. Afterwards, I set his role to normal user, he can still access the admin features because his localStorage contains the role of AminUser.
Can someone suggests a correct way to implement authorization so that the token is updated on user end?
Thanks.
What is your trigger for changing the user's authorization? If you're saying that you're opening your database client (Say for example MySQL or PostgreSQL) and manually changing the authorization for the user, then there's no way your server or your client to know of that change (As far as I know at least) and they cannot react to that particular change.
If your trigger was some request sent by the user, say logout or change authorization, then you should respond with the new token for that particular request and store it, easy peasy.
If your trigger wasn't related to your client, and it's somehow something happening on your serverside, then you should have a socket opened between your server and your client, and emit that change from your server to your client.
That way you ensure the client is always up-to-date.
But that's still not enough, because yeah you're keeping the client up to date, but what if he saved the token and replaced it after your update? He/She can still access admin features even though you told them they're just normal users. For that you're gonna need to validate every request done by any of your users, and check if they're allowed to make that request in the first place.
You cannot really trust clients. You should find a way to invalidate your jwt tokens. Your client should get a new token when you reject them. You can rotate your tokens using refresh key.
In order to do that:
Keep your token lifetimes short
Or:
Store blacklisted tokens in the database and reject the invalidated tokens.

is passport required when using JWT

Very basic question but probably I miss something very big in the big picture.
I cannot figure out whether passport.js is needed or not when using JWT auth. Most examples have it but I fail to see the need.
In my app, there is a /login route and once the user authenticates successfully ( local auth, I check user, a hash pair in the database) I create a token with user id in it, set an expiry, sign it and send it back as the cookie in the response. Then I check the req cookies, decrypt and if they contain user id and not expired, I consider the request authenticated. (also traffic is https only if it changes anything)
Am I doing something wrong here as I don't have passport etc. in the process?
No, JWT (RFC 7519) is a standard. passport.js is an implementation that uses JWT. It is not required.

Resources