Do I use a refresh token? - node.js

I have an application that doesn't have user accounts so doesn't need a login. I'm currently authenticating using JWT via a /get-token endpoint in my api that's called as soon as the UI starts and returns a bearer token that's used for the calls for the calls moving forwards/
When that token expires, i'm a little confused at how to handle that. I was thinking using a refresh token but all the tutorials i've seen are passing the refresh token back to the UI, isn't that unsafe? I was always under the idea that the refresh token was internal and is only used on the server to refresh expired tokens.
What's the best way to handle this?

Refresh tokens carry the information necessary to get a new access token. In other words, whenever an access token is required to access a specific resource, a client may use a refresh token to get a new access token issued by the authentication server. Common use cases include getting new access tokens after old ones have expired, or getting access to a new resource for the first time. Refresh tokens can also expire but are rather long-lived. Refresh tokens are usually subject to strict storage requirements to ensure they are not leaked. They can also be blacklisted by the authorization server.

Related

get access token with access token?

From what I understand so far about access token is that in Code flow, Client could get access token with either authorization code or refresh token.
But.. can it get new access token with access token it holds before the token's expired?
I read RFC6749(1.1 ~ 1.4, 4.1, 4.2, 5 sections only for the sake of time) and I couldn't find such that
"access token must get issued by only explicit resource owner's grant or refresh token"
So I've been thinking..
How about issuing access token with access token.
What's wrong with this?
I'm almost noob to OAuth and learned it with only internet so I might totally misunderstand something D:
please enlighten me.. thanks!
You cant use an access token to get a new access token. Access tokens are self contained bearer tokens which grant you access to some data. (denoted by scope) For security reasons access tokens have a limited life time. Once it has expired you can not longer use it.
Consider if someone with a malicious intent got a hold of your access token. They can then use this to access the data, but only for a limited amount of time. Once the access token expired they would no longer be able to access that data.
refreshing access
The first step of the auth process gives you an authorization code, this is a one time code extremely short lived probably five minutes and can only be used once. When you exchange this you will get an access token and a refresh token if you requested offline access.
Refresh tokens can be used to get a new access token. You can use it to get access at a later date without requesting access of the user again. To get a new access token though you need to have the client and i and client secret that were used to create the access token in the first place, and in some cases you need to have access to the server that the redirect uri is residing. This way if the same a malicious person got access to their refresh token they cant use it to get a new access token unless they have your , client id, client secrete and server access.
You may find this interesting Understanding oauth2 with curl
TLDR
To be able to revoke access. Refresh token is used for that.
Here is my understanding. Access token are not retained by the auth server that issued them. They are very large in size and there may be a great number of them in a general case, one per scope or a set of scopes. Refresh tokens are short opaque strings and are retained by the auth server. They can be invalidated by the auth server to revoke authentication if a user's system has been found compromised. If an attacker obtained access/refresh token and used them from a different IP, for example. In this case the auth server will set a flag against the retained refresh token and will not refresh an access token without re-authentication.

Access/Refresh token confusion

I've been doing a lot of reading on this subject and I can see that there are many different opinions and approaches to authenticating using JWT.
My understanding is as follows:
In its simplest form, a JWT authentication mechanism should:
Verify username and password.
Create a signed JWT access token containing information (depending on the app's needs) on the user.
Send that token in the response.
The client then stores the token (which from my understanding there is some debate whether a secure cookie or localStorage is more secure), and sends it with each request's headers.
The server can then authorize the user using middleware verifying the JWT. No state, all information in contained within the JWT.
Assuming the JWT has no expiration (or perhaps a very long expiration date, maybe a couple of months), it sounds good because I can provide the user a persistent logged in state for a long time. The concern is, to my understanding, if the JWT was to be stolen, it is essentially an unlimited access card and a huge security breach.
So that's where the refresh token enters, the server issues both refresh and access tokens (refresh token with a long/unlimited expiration and the access token short).
The server database holds some kind of table of valid refresh tokens (so that if one is stolen it can be invalidated easily) and when issuing a new access token, validates the refresh token.
This also adds the need to add some sort of countdown mechanism on the front end where a refresh request is to be sent to the server prior to the access token expiration date so that the user won't be logged out.
And my question:
Why? If we go through all the trouble of creating a db table for refresh tokens, why not just make a table of valid access tokens and invalidate them if needed? How is that less secure than using refresh tokens?
Thank you
Access tokens aren't primarily used to provide extra security, but to provide efficiency and decoupling.
An access token can have a very short lifetime - maybe even less than a minute - but be used to authenticate multiple requests to different services within that time. Those services don't need to have any access to the authentication database, because they can trust the access token until its expiry date; that makes them faster and simpler.
For instance, if you're using a dynamic page with lots of AJAX requests, that might run in very quick succession. Those AJAX calls might be implemented as serverless functions (e.g. AWS Lambda), or as standalone scripts in different programming languages on different servers, or you might just want to make them as efficient as possible, and avoid any database access. The only information that needs to be shared between them is a public key to verify the signature on the JWTs they receive.
From a security a point of view, this is a trade-off: on the one hand, an access token for a user whose access has been revoked can still be used until it expires; on the other hand, the long-lived refresh token is transmitted much less than a traditional session token, so there are fewer chances for it to be intercepted.
To address your concrete concern:
This also adds the need to add some sort of countdown mechanism on the front end where a refresh request is to be sent to the server prior to the access token expiration date so that the user won't be logged out.
No "countdown" is needed. The code that has access to both tokens simply looks at its current access token before using it; if it has expired, or is about to expire, it requests a new one using the refresh token. It then gets a new access token, and probably a renewed refresh token - the expiry date on the refresh token represents how long the user can be idle before they are automatically logged out.
We don't need to make a table of access tokens and it is dangerous to secure.
We have to save only refresh token and add one field for valid/invalid in the table. And send access token and refresh token to the client side.
The clients send access token with each request's headers.
The server can authorize the user using middleware verifying the JWT.
After some time, the access token will be expired(access token's expired time is shorter than the refresh token's expired time).
The client sends refresh token to server.
Then the client will get new access token using refresh token(refresh token should be recreated, in other words, we can use only one-time refresh token, we have to update table of refresh token with new refresh token).
The client can get new access token and refresh token.
I hope it will be help you.

jwt access token and refresh token flow

here is my auth's flow:
The user receives two tokens (access token with expiration time and refresh token without expiration time) after logging in
for each user , The refresh token is stored in the database in a json column called refreshTokens(which is an array).
on the client side, Both access token and refresh token are stored on the local storage.
when user needs to be verified, If the access token is expired, a new access token is created using the refresh token and sent back to the user and keeps the user logged in.
When the user logs out, the refresh token stored in the database (in the refreshTokens list) is removed.
my questions are:
is this flow, secure?
do i need to save refresh token on the cookie or is local storage good enough?
That flow is according to how OAuth works and how tokens can be stored in a secure way, so "yes" to both questions. The part that is missing is how the tokens are obtained in the first place: for that the Authorization Code grant type using PCKE is the preferred way, over the legacy Implicit grant type.
An important part of this flow being secured is that in point 4 you use the list of refresh tokens kept in the database to verify that the RT was not revoked. Other than that it looks ok. You can add more security by adding expiration times to refresh tokens. Then, even if the user doesn't actively log out (you don't clear RTs from the DB), the RT will not be usable after some time.
Keeping the tokens in local storage is good enough in my opinion.
Few stuffs that popped up in my mind while reading this :
Refresh Token also needs expiration time. In fact, I consider refresh tokens as a double edge sword. Imagine a scenario where a person gets access to the refresh token, not only he gets access to the resources, he will practically gain more time with the resources. I prefer to re-generate refresh token along with access token when refresh token is being used to re-generate the access token. And, also set an expiry to it.
It is cool to store the refresh token in database. However. I do have an alternative though, you can easily use RSA algorithm and then do token generation using private key and verify using public key. This is yo mitigate the scenario of needing to store the refresh tokens.
On client side, local storage is a BIG NO from my side. What I prefer is that you use HttpOnly Cookies and set flag as true. HttpOnly Cookies are not rendered in JS and is sent to server securely as per Http protocol. This is fix the chances of compromising tokens.
Your rest concept of it is good enough.

how to do authorization (nodejs, express) with two tokens (access/refresh)

Good evening, I ran into a problem that I need to make authorization more secure and without re-logging. I read on the Internet that you need to use two tokens (access and refresh), but how to properly do authorization with them. You can advise a resource where competent authorization with two tokens is made.
My Tech Stack:
MongoDB
ExpressJS
ReactJS
NodeJS
If you request authentication with offline_access scope, you'll geta refresh token in addition to an access token. Save this refresh token to the database and whenever you need to make another call on behalf of the user you can
Make the call using your existing access token. If you don't get a 401, then you're good.
If you did get a 401, your token is probably expired and then you can call the token end point on the authorization server with the refresh token and grant_type=refresh_token to get a new access token and try your call again.
Might make the most sense to always request a new access token using your refresh token before you make another call.
To my knowledge you only deal with access tokens for authorization. The refresh token is only there to refresh an expired access token. The refresh token is exchanged for a new access token - without needing to present authentication credentials again. The call also (typically) takes a fraction of the time than re-authenticating.
as soon as the user log-in, give it two tokens refresh and access, store the refresh token in the database, give access token a expire time (5-10 min approx or less depending on your requirement).
for each request user will use the access token and for each request backend should check for the expired access token.
if the access token is expired, user will get a new access token by sending the stored refresh token to the backend(using a dedicated endpoint), backend will than check whether the refresh token is present in the database or not, if yes a new access token with new expire time will be sent in the response.
the cycle will continue until the user logs-out, in that case the refresh token will be deleted from the database and after some time access token will also get expire.

How to handle JWT refresh token in a mobile app environment

I am implementing JWT inside a client mobile app with a separate back-end server, and I am looking for an optimum way to use refresh tokens without too much server calls and while keeping a good user experience.
I am new to implementing such a mechanism, and I am confused about many things, so what I am really looking for is a solid conceptual solution to secure the user access to the app, and keep him at the same time logged in indefinitely.
Any correction or suggestion would be most welcome:
Why refresh tokens anyway?
Using a JWT access token alone might compromise the user security: If an attacker holds the access token, he might run feature requests whenever he wants. Even when applying an expiry date to the access token, if the server issues a new access token whenever the old one expires, the attacker will receive this new access token using his old one, and keep accessing the user features.
Refresh tokens stop the attacker once the user regains access to his account using his login/password: When the user uses the app and the server detects that his refresh token is invalid, he will be logged out and a new refresh token and access token are issued after he's logged in with his credentials. The attacker won't be able then to use the old tokens.
My first question would be:
I. Regardless of how the attacker gets hold of the tokens from the user environment, would he be able to use them indefinitely as long as the user is still inactive and isn't logged in again with his credentials to create new tokens?
What about when the tokens are refreshed asynchronously?
Let's imagine a scenario where the user is inside the app, and at least two server calls are run asynchronously:
"Service1" makes a server call with an expired accessToken1 and a refreshToken1, and the server responds by sending a new accessToken2 and refreshToken2
Before receiving the "Service1" response, "Service2" makes an other server call with accessToken1 and refreshToken1, the server compares refreshToken1 to the previously saved refreshToken2 and finds them different. It responds then with an Invalid refresh token response, and this causes the user to be logged out!
To avoid this problem and keep the user logged in, there could be a centralized authentication service that checks first the validity of the tokens before any server call is made. Which means that any call won't be executed unless the authentication service is idle, or wait for the new tokens if it's already loading.
My second question here is:
II. Having such a service to avoid the asynchronous refresh token problem means more round trips to the server, which might prove costly. Is there a better solution?
There are some steps to login / revoke access to an api:
When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
The access token will have less expiry time and Refresh will have long expiry time.
The client (Front end) will store refresh token in his local storage and access token in cookies.
The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
Once the refresh token is expired, the User will be logged out.
JSON Web Tokens are a good way of securely transmitting information between parties. Because JWTs can be signed—for example, using public/private key pairs—you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
What about when the tokens are refreshed asynchronously?
that supposed be done with a single request to an endpoint, so there is a single accessToken
Having such a service to avoid the asynchronous refresh token problem means more round trips to the server, which might prove costly. Is there a better solution?
i think that's the best & secure solution for mobile and serverless apps, token are like ssh keys must be kept secure all the time :)
for more information check [question]: JWT refresh token flow
Here's the official introduction to JWT

Resources