Is it secure to store a refresh token in the database? (To issue new access tokens for login purposes). Or is there a method to do it easier? - jwt

Currently im trying to gather knowledge on how to implement an auth system (a login) . And during my research i've tried to implement a JWT based solution in my backend.
I have an express server which allows me to register an user , storing its password (encrypted) and its email.
After that on login, it generates an access token (short lived, 5min) , in order to access protected routes, and a refresh token (long lived, 7 days), in order to generate new access tokens once the previous expire.
In my current implementation, im storing the refresh token in my database, so I can use it every time I want to generate a new access token.
But is that secure? As far as I understand, storing an access token in my database is dangerous, so its better to create a short lived cookie stored one. But... the refresh token? As far as i understand it would be dangerous since it basically allows to generate new access tokens, so I dont see the point of why not simply storing a long lived access token in my database, an generating a new one in every login.
Whats is the refresh token for then?
Since im following some tutorials in order to achieve this, this is how my refresh_token route looks
//get a new access token with a refresh token
app.post('/refresh_token', (req, res) => {
const token = req.cookies.refreshtoken
//if no token in request
if(!token) return res.send({accesstoken : ''});
//if we have a token we verify it
let payload = null;
try{
payload = verify(token, process.env.REFRESH_TOKEN_SECRET);
}catch(err){
return res.send({accesstoken: ''});
}
//if token is valid check if user exist
const user = fakeDB.find(user => user.id === payload.userId)
if(!user) return res.send({ accesstoken: ''});
//if user exists check if refreshtoken exist on user
//Is this really necessary? <-------------------------------------------
if(user.refreshtoken !== token){
return res.send({accesstoken: ''})
}
//if token exist create a new Refresh and Accestoken
const accesstoken = createAccessToken(user.id);
const refreshtoken = createRefreshToken(user.id);
user.refreshtoken = refreshtoken;
//send new refreshtoken and accesstoken
sendRefreshToken(res, refreshtoken);
return res.send({accesstoken});
})
The arrow comment is where I have my doubts, ok its returning an empty access token if my database table user (its a mock database so an array so far) , doesnt have stored a refresh token. But why would you do that? Is that used to not let arbitrary users generate access tokens? As far as I understand thats the only reason of why would I do that.
But again then, isnt it dangerous to store in a database? WHy not simply store the access token then make it a long lived token, and generate a new one in every login?
Is there a method to do it simplier than with jwt?

Why access tokens should be short-lived: if you want a decentralised auth flow (authentication service signs a token, other services can verify if it's valid using an asymmetric public key), you want that token to be short-lived because it cannot be blacklisted in case it's stolen (an attacker can use it until it expires). You can of course blacklist access tokens using i.e. Redis, but your auth flow won't be decentralised anymore. All services will have to validate that token using the asymmetric public key AND check if it's blacklisted or not (better just ask authentication service if it's valid or not).
This is how I would go about it:
5 minute access token as JWT (self-contained, don't need to store it
anywhere).
7 day refresh token for one-time usage: generate random secret (don't need to sign it/encrypt it), store it in Redis with a 7 day TTL (or MySQL with a valid_until timestamp). On /refresh_token validate the provided token (check if it's in Redis/MySQL) and delete it. Generate a new access and refresh token pair. (I like to rotate refresh tokens as well, it makes it a bit more secure: it's probably already rotated=invalid if stolen)
This way the auth flow stays decentralised and refresh tokens can be revoked if they are stolen.

Refresh tokens should be encrypted in storage. The OAuth 2.0 Threat Model and Security Considerations RFC goes into this:
4.5.2. Threat: Obtaining Refresh Token from Authorization Server Database
This threat is applicable if the authorization server stores refresh tokens as handles in a database. An attacker may obtain refresh tokens from the authorization server's database by gaining access to the database or launching a SQL injection attack.
Impact: Disclosure of all refresh tokens.
Countermeasures:
Enforce credential storage protection best practices
(Section 5.1.4.1).
Bind token to client id, if the attacker cannot obtain the
required id and secret (Section 5.1.5.8).
And then the referenced section 5.1.4.1.3:
5.1.4.1.3. No Cleartext Storage of Credentials
The authorization server should not store credentials in clear text. Typical approaches are to store hashes instead or to encrypt credentials. If the credential lacks a reasonable entropy level (because it is a user password), an additional salt will harden the storage to make offline dictionary attacks more difficult.
Note: Some authentication protocols require the authorization server to have access to the secret in the clear. Those protocols cannot be implemented if the server only has access to hashes. Credentials should be strongly encrypted in those cases.

Related

Flutter-What is the point of using bearer-token or something

I read something like this:
1-Once a user logs in, you can generate a token and store it in MySQL database and share the same token with the response of login API.
2-Store the token using shared-preferences.
3-When a user opens the app, check if the token exists if it does, then send the token with all the APIs inside the request header which requires the user to be logged in.
But what is the point of using token if i was keeping it in database.Eventually this token related with userid and with this userid everthing can be reachable.So I want to ask why should I use some token to keep user loged in instead of user email or something.
Using token is much more secure and useable. Storing just token more secure becase in case of leak, the token can be revoked or something. On the other side storing user's username and password is security risk. Also, most of the services use tokens on their API's and there is no username+pass authorization. For example whole OAuth2 concept is built on top of this. In short, tokens are much more secure and flexible.
Optimal usage of bearer token using as a set with an access token and refresh token. While you are passing access token on header while you are making HTTP request typically access token dies frequently especially when security is a prominent feature of the app, like banking apps. When a user makes an HTTP request and if the access token is dead then you should refresh it via another API call with the refresh token and return the same API call with the new access token.

API rest with jwt for authentication. Why do we need a refresh token?

So, i'm trying nest js for a side project. Reading a lot lately about jwt authentication flow. Conceptually, the flow would be something like:
Client logs in and receives and access token and a refresh token. Access Token will be short lived and will be stored in memory, not in localstorage, to reduce the risks of being stolen.
Refresh token will be used only when the access token is expired to get a new one. The new one will be stored in memory. The refresh token will be stored in an httpOnly cookie, so no javascript access will be allowed hence improving the security.
Everything is cristal clear, but, my question is... why do we need the access token and why don't we always use the refresh token? In the end, if we are trusting the refresh token to generate new access tokens... why don't we simplify the whole thing and use only the long lived, stored in an httpOnly cookie on every request?
I mean I get the whole process, I just don't get why is not "secure" to use the token stored in an httpOnly cookie every time.
Can anyone share some light here?
Thanks!
You use the access token to access the API. It contains the necessary claims to authenticate and authorize the request.
The refresh token is a separate token that you use to renew the access token and you can not use the refresh token to access any API, as it is typically just a random string without any specific meaning (no claims).
The refresh token is never sent to any API and having separate tokens gives a better separation of concerns. By using refresh tokens, we can have short-lived access tokens, so if the access token is stolen, it can only be used for a short time. The refresh token is stored in a more secure way and it is only used between the client and the identity provider, so there is less risk that it will be stolen or intercepted.
Some platforms (like ASP.NET core) stores the token by default in the session cookie) but to secure it it is encrypted using strong encryption. This means that the hacker or browser can't see the actual tokens inside the cookie.
More you travel, more you exposed.
As you know the refresh token is meant to be used in case of short lived access token expiration. The idea for the use of two tokens is very simple. As access token (short lived token) will travel more frequently over the wire, increasing it chances of getting it caught by external parties. Therefore, short life expectency of access token will deny the access to the resouces for longer run in case of compromisation.
If the refresh token is secured, why don't we use just the refresh on
every request?
Nothing can make the refresh token secure. It's totally client responsibility to store it in secure location/storage for later use.

Does I understand access and refresh token technique for authentication correctly?

After doing some research in using JWT with Access Token and Refresh Token for authentication. I understand this in this way.
After login, return to user Access Token and Refresh Token (using same technique JWT for both).
Saving Refresh Token in Database (one User can have multiple Refresh Tokens for multiple devices).
Whenever user sends a request with invalid Access Token, check Refresh Token and call another api to get new Access Token (doing this in client side). After that, call api to get data again with new Access Token.
If Refresh Token is invalid, deleting its record in database and user must to login again to get new Refresh Token.
Does I understand Access and Refresh Token technique correctly? Please give me some advices. Thank in advance.
Of the 4 steps you listed, some look more or less correct while others do not. I will begin this answer by giving the premise for why refresh tokens were created and what is their main purpose.
Using the JWT pattern with only access tokens, there is a potential usability problem when the JWT token expires. Consider as an example a banking website. When a user logs in, he receives a JWT token with a certain expiry (typically stored under the exp key in the claims section of the token). If the token is given say a 5 minute expiry, then from a usability point of view, it means that the website would have to force the user to manually login every 5 minutes. Obviously, this is not the best user experience, because it means that a user who happens to be in the middle of some business process when the token expires might lose all that work. This is where refresh tokens step in to alleviate this problem.
Using the JWT pattern with refresh tokens means that the user receives both an access and a refresh token. A typical workflow here might be:
After login, return to user Access Token and Refresh Token (using same technique JWT for both). The receiver notes when the access token is set to expire (say 15 minutes).
As the expiry of the access token approaches (e.g. 10 minutes), the UI will send the refresh token to the backend to obtain a new access token (and refresh token). This could be done explicitly, e.g. on a website which displays a popup asking if the user wants to continue. Or it could be done in stealth mode, with a REST call being made under the hood to get the new access token.
For the edge case where the refresh token cannot be used to obtain a new access token, then the very next user action which requires authentication would fail. In this case, the user would have to redirected to the login page. But, as this case should generally be rare, it does not disqualify the refresh token pattern.
I would also point out that storing the access/refresh tokens in the database largely defeats the purpose of the JWT pattern. One major reason for using JWT is that it pushes the user session state out of the application and onto the user. By storing tokens in your database, you are totally making your user sessions very stateful, which has all sorts of potential drawbacks. Consider using the suggested workflow above to avoid doing this.
The way I see it, your refresh token needs to be stored and associated with the device and the user.
Example:
User Logs In in Device A
Call Login endpoint
Validate user is valid
If valid, generate a refresh token associated with the userid & device
id
store required data to your table or storage engine (user_sessions..etc)
user_id | device_id | refresh_token | expires_at
Return the payload with access_token, refresh_token , access_token_expires_at, refresh_token_expires_at
Front-end, store the payload
when consuming a resource, check the following
If refresh_token_expires_at > now then logs them out , show your session is timeout (or you can have a never expired refresh_token.. ex. refresh_token_expires_at can be 0)
if access_token_expires_at > now then call refresh token endpoint along with your payload.
on the refresh endpoint, validate the call and check the refresh token against the data stored.
if refresh token is valid for this user+device, generate a new access_token
return the access_token and its expires_at
If the refresh token is INvalid , return invalid
front end will log the user out.
** in any case, if a refresh token was compromised, it will be only for that particular device/user. A user can then deactivate or remove the device from their list. This action will invalidate the refresh_token on their next refresh call.

is it a good idea to put expired tokens to blacklist table?

To begin with this is how my current auth flow looks
User logs in
User gets a refresh_token assigned and stored in the database (long lived 7d)
Client receives an accestoken (Short lived, 2h), and stores it as a cookie. Client also receives the userId AES encrypted, and stores
it as a cookie.
As far as the access token is not expired, the user keeps using the token to navigate the website
The token expires
The expired access token gets send to a refresh endpoint, so is the userID (Aes encrypted) both currently stored in out cookies.
The server decrypts the userId and retrieves the refreshtoken that corresponds to the user by selecting the refresh token from the database using out userId.
Now we have in the server our refreshtoken and accestoken, so we refresh the token, and send back the new accesstoken. We also generate a new refreshtoken and overwrite our old refreshtoken in the database with the new one.
My question is basically related to that last step. Since those refresh tokens are still technically valid, since they have a long expiration time. Can I create a table in my database named "blacklisted_tokens" or something like that, and store there the values of the token? And then right before generating a new access token it should prior to that check if that refresh token is or isnt in that database, meaning that it will be blacklisted.
This is the authflow diagram
My question is basically related to that last step. Since those
refresh tokens are still technically valid, since they have a long
expiration time. Can I create a table in my database named
"blacklisted_tokens" or something like that, and store there the
values of the token? And then right before generating a new access
token it should prior to that check if that refresh token is or isnt
in that database, meaning that it will be blacklisted.
it's not recommended to do that as because, probability of generating 2 same token is low and adding NOT necessary additional processes to your back-end is not a good idea and has performance issue in large scale Token re-generation(a lot of users).
And also, Tokens are along with an identity(id) in which reduces security risks.
if i were you, i would just re-write new-token to old-token.
The most important type of cyber attack which threaten Tokens is The Sniffing attack and by doing below steps actually the probability of this attack goes almost to zero:
SSL certificate
Expiring Token and re-generation
Salty requests
Salt
In cryptography, a salt is random data that is used as an additional
input to a one-way function that hashes data, a password or
passphrase. Salts are used to safeguard passwords in storage.

Should OAuth access token be hashed before storing in the DB server side?

I am implementing an OAuth server that supports Resource Owner Password Credentials Grant flow. Once I generate the access token should I hash the token before storing it in the DB? My main concern if I hash is, if the token request comes a second time after I have generated the token and associated it with the username/password combination, it would be impossible to send the token back as it has been hashed. Am I supposed to throw an error in that case? The RFC is silent about this.