Anton Myrberg Anton Myrberg - 3 months ago 9
Javascript Question

What is the best way to update the accessToken in the app with the new accessToken?

Before getting to the actual question



Alright I have created my own authentication system that I am going to use on my API.

Simple explanation:

On
/signup
the user types in username, password etc... the API grants the user with
tokens
which are stored in the user document in the database. The API also returns with a response body with the new
refreshToken
and
accessToken
, my thought here is so the app easily can store the tokens on the phone for later calls to the API.

/login
is pretty much the same thing except you only provide username and password.

One of the routes in the API is the
/article
which you can
GET
&
POST
.

Now if you try to for example
GET
the
/article
and your
accessToken
is expired the API will automatically call
/token
which requires the
refreshToken
in the header, the
/token
will then grant you a new
accessToken
and request the same route you were trying to get (in this case
/article
) with the new
accessToken
in the header.

The question:
What is the best way to update the
accessToken
in the app with the new
accessToken
?

router
.route('/article')
.get(
AuthenticateController.authenticate,
NewsController.getAllArticles,
AuthenticateController.sendAuthorize
);


This is how I do it now,
AuthenticateController.authenticate
authenticates the accessToken and checks if it is expired and all that then calls
next()
.

The
NewsController.getAllArticles
gets all the articles and also calls
next()
so the
AuthenticateController.sendAuthorize
can run and return the new
accessToken
in the response header when a new one is granted (I thought this would make it easier to obatin the new token in the app). This is where my question comes in because I can't call
next()
on every route because on some routes the main function already returns a response and that means that
next()
cannot be called which means
AuthenticateController.sendAuthorize
will never run. I want the
AuthenticateController.authenticate
to be the only middleware required to authenticate the user.

Answer Source

Instead of waiting until the last route to send the new token, you should move the sendAuthorize middleware above the route's main response (or combine it with authenticate), and instead send a 401 Unauthorized response with the new token. Then, update the token on the client and resend the request.

It seems like a silly practice to send a valid response with an invalid accessToken anyway. You're going to want to invalidate tokens eventually (I.e on log out or password change), and you don't want users to be able to make unauthenticated requests.