Why don't APIs use access token instead of refresh token? - api

I've already seen
Why Does OAuth v2 Have Both Access and Refresh Tokens?
https://auth0.com/blog/refresh-tokens-what-are-they-and-when-to-use-them/
As per my understanding, this is how OAuth v2 works:
1) user sends his credentials to the server which validates it and returns an access_token and a refresh_token
2) user sends this acsess_token along with further requests to identify himself
3) when the access_token expires, the user sends another request to the server with refresh_token and other required parameters asking for a new access_token and refresh_token
Here's my question:
What's the need of a separate refresh_token ? Why not send the old access_token ( which is about to be expired anyway ), for a new one ??
What's the additional advantage of using a refresh_token ?

The access token is, in theory, more in play. It could be in a browser, on the server-side of a client, on the authorization server or on a resource server. The access token will be attached to every API request whereas the refresh token should be used much less frequently.
A couple quotations from the web...
Unlike access tokens, refresh tokens are intended for use only with authorization servers and are never sent to resource servers.
https://www.rfc-editor.org/rfc/rfc6749#section-10.4
[Refresh tokens] are usually subject to strict storage requirements to ensure they are not leaked.
https://auth0.com/learn/refresh-tokens/
Basically, if we only had access token, the attack surface would be greater.

Related

JWT auth flow using access token and refresh token

I'm working on a project (nothing production-level, only for leveling up my skills) and I'm using JWT to handle authentication.
From what I've read, using a JWT only as an access token is quite unsafe, and hence we need refresh tokens. So, on login, the server returns an access token and a refresh token (which I will be storing in an httpOnly cookie). The access token expires in a short time, but the refresh token is used to get a new one when it does.
My question is, when do we use the refresh token to get a new access token? Is it when the user wants to get a protected resource and finds that the access token is expired (and the refresh token has not) or do we send a new access token each time the user wants to get the protected resource? I'm confused about when and where the refresh token comes into play.
(I'm using React for the frontend and Nodejs for the server)
You're using some security token so it mean that your system has some protected resources. Those resources can only be accessible on successful validation of the token. As you're using the JWT Token (usually for stateless authentication) and your system is granting both access_token and refresh_token to the client, so on server side you can use some authentication interceptor to validate the access_token in the each private request and return some error code on token expiration. On the client side you could also use some filter which should capture the error code and by utilizing the available refresh_token it should request for new access_token from the server. In case of refresh_token expiration your system should follow the route of fresh authentication.
The refresh token can be used at any time to request a new access token. Checking the validity of the access token before he request is one way of accomplishing that. Another common practice is to refresh the access token if it is within a certain timeframe of the current token expiring. A simple cronjob can work in this case. If you assume the access token is not used in multiple places (which it shouldn't be) then the current access token can be invalidated when the new access token is created. Also, for maximum security, the refresh token should be replaced with the access token. This limits security risk around a long-living refresh token becoming compromised.

Should access tokens be refreshed automatically or manually?

In the last few days I've been reading on Authentication with refresh and access tokens, but this is one thing I can't find the answer to. Let's say an expired access token is sent. Should the backend automatically refresh it (if a refresh token was provided), or the refreshing should only be done at a refresh endpoint?
As an example, consider the two following auth flows:
Automatically Refreshing
User authenticates with username and password. The API sends back a short lived access token containing his data, and a long lived refresh token.
For every request that requires authentication/authorization, the user will send both tokens on the request headers.
If the access token is expired, the API will check if a valid refresh token was sent, if it is active and if it belongs to the same user as the access token. If everything looks good then it will sign a new access token and update the response headers with it.
Front-end doesn't have to worry about refreshing the token, but it still has to look up response headers after each request to check if a new token was sent.
Manually Refreshing
User authenticates with username and password. The API sends back a short lived access token containing his data, and a long lived refresh token.
For every request that requires authentication/authorization, the user will send his access token.
When the access token expires, the user will send his refresh token to the refresh/ route. The API checks if the token is valid. If everything looks good, it returns a new access token.
After every request, the client has to check if the token expired, and if it did it will have to perform a new request to refresh the token. More requests are being made to the server, but on the other hand responsibilities are better separated, since auth route is only responsible for handling access tokens, while the refresh token handling lives in another route.
I've had some hard time finding resources on the subject, so I'm not quite about sure which solution is better, or even if the solutions I described are correct at all. If I had to pick one, I would go with Automatically Refreshing, since less requests are made, and the client side usability looks better, but as I said, I'm not 100% on this, and thus I'm making that thread.
How should access tokens be refreshed?
It feels to me that you are missing a role here, which is that of the Authorization Server (AS):
UI redirects to AS to authenticate the user via password
AS issues an access token and refresh token, then returns them to the UI
UI calls the API for a while with the access token
Eventually the access token expires and the API returns a 401 response
The UI then calls the AS with the refresh the token to get a new access token
The UI then retries the API call with the new access token
Eventually the refresh token expires and the refresh attempt will fail
The UI then redirects the user to sign in again and the cycle repeats
It is always the client's responsibility to refresh tokens and only the access token should be sent to the API. The API's only OAuth job is verify the access token and authorize based on its contents.
It is possible that you have an API that is doing the job of the Authorization Server. I would aim to separate these roles. If it helps my Messages Blog Post has a lot of detail on the messages in a full UI and API solution.
The implementations of the OAuth2-protocol I know use the flow you are describing under "Manual Refreshing". The client has to care himself about the refreshing.
The client can either check the access_token if it is still valid before every request or do a refresh after a failed request due to an invalid token response.
The access_token is short lived and so the risk sending it with every request and having it eavesdropped and misused is limited. The refresh_token is long lived. If you send the refresh_token with every request an attacker has a much greater chance to get hold of it.
If you send both token with every request you would not need the distinction between these two types. You would work with one long lived token only.
Following is the Main Disadvantage of using Automatic Refresh Token Rotation Scheme :-
Let's say the Client makes 2 API calls (API A and API B) at the same time. At the time of triggering these two API calls, the access token was expired. Both of these API calls are carrying the same expired access token and the refresh token (let's assume this refresh token is valid).
Let's assume API A gets handled by the server first. According to the Automatically Refreshing Scheme, the server will check the API A's access token, if that token is expired, server will check the refresh token and if that refresh token is verified (this refresh token is present in the database too), the server will create a new access token and a new refresh token (the refresh token that came with the API will be deleted from the database and will be updated with this new refresh token). These new tokens will be returned to the Client.
API B will follow the same flow. BUT its Refresh Token will be invalid because during the handling of API A, the refresh token was replaced in the database by a new token. API B's Refresh Token is not present in the Database and thus this request will fail.
If you have multiple APIs being called at the same time, Automatic Refresh Token Rotation Scheme will fail as the First API request will replace the Refresh Token when renewing the tokens and the remaining API requests will be coming with a Refresh Token which is not present in the Database !
My experience has been that the OAuth2 access_token requests dont like extra data meaning that you wont be able to send both the access_token and the refresh_token. That would lead to the Manual Refreshing scenario youve described as the only option

long-lived access token vs short-lived access token & refresh token pair

I read a few articles, but still not able to derive a good enough understanding. So far, I understand that:
After successful authentication, server sends back an access token (ex. jwt) that a client uses to make authorized subsequent requests.
But this access token can get stolen from the client. So we'd make it short-lived. And, we use refresh token to renew the access token without having the user to follow authentication process again.
Questions:
Where do we keep the refresh token? Do we send it back to the client on initial successful authentication? Or do we store it on the server somewhere (DB)?
If we're sending it back to client and the client is using the refresh token to generate more short-lived access token, than that refresh token can also be stolen. How does it make the process secure? Wouldn't keeping a long-lived access token safe suffice?
Thank you.
To answer your first question, Ideally refresh token should be returned to the client along with the access token.
In order to make your access token/refresh token more secure you could add in some browser specific metadata into the JWT that you generate and verify on the server side to avoid token side jacking.
To learn more on some good REST security practices you can refer to this link
https://github.com/OWASP/CheatSheetSeries/tree/master/cheatsheets

Custom (Non-OAuth) Refresh Token Implementation

I'm working on an application that uses a token-based authentication system, where the user provides their username / password and receives a token in return (the token gets saved to the database as well). Then subsequent requests will include this token as a custom header and we can use this to identify the user. This all works fine.
Right now if the user doesn't login for 3 days, we expire the token. I was reading a little about refresh tokens in OAuth and I was wondering if I could somehow implement something similar. i.e. when providing the auth token, I also provide a refresh token which can be used later to request a new auth token. In terms of security though, it seems quite similar to just never expiring the user's auth token in the first place. Should I be sending additional information with the refresh token to validate the user?
In OAuth2, the resource server and authorization server are often not the same.
The refresh token is sent back to the client when the access token is issued and when the token is refreshed. The client needs to authenticate itself (using client id and client secret) to use the refresh token. The resource server never sees the refresh token.
Also, access tokens are not stored at the server side as they have a limited lifetime. Refresh tokens are stored and can therefore be revoked.

How to make Google sign-in token valid for longer than 1 hour?

I have implemented google sign-in successfully.
I am able to authenticate user and in response I receive token. However the token expires in 1 hour.
expires_in: "3600"
I tried searching in the docs - https://developers.google.com/identity/sign-in/web/reference - but cannot find a paramenter to extend the lifespan of the token.
What I'm actually trying to do?
https://developers.google.com/identity/sign-in/web/backend-auth
after a user successfully signs in, send the user's ID token to your server using HTTPS
I'm sending token with each request to the server:
endpoint/get?access_token=" + access_token
And then on the server I'm calling https://www.googleapis.com/oauth2/v3/tokeninfo
So I have a token, every request is authenticated, but after 1 hour of working the tokeninfo method returns false and I need to re-authenticate the user.
In my code I circumvented that by storing all the historical access_tokens and if client uses old token I check against historical data and manually issue new token using refresh_token (one of my permissions is to grant offline access)
So yes, I'd be very interested to know:
How to expand lifespan of the access_token?
OR
Given the limited lifespan how to ensure requests are authenticated on the backend?
As #DaImTo noted, you can't extend the life of an access_token. You can get a new one using a refresh_token, but often if you're trying to do this client side and have a server, you should re-think your approach.
It sounds like there are two "authentications" that you're doing here - the client authenticating against the server, and the server authenticating against the Google service. Right now, the server should be holding onto the refresh token - so it can always re-authenticate against Google. It sounds like you're wrestling with how to authenticate your client against the server after the auth_token timeout.
In general, the client shouldn't send the access_token to the server, nor the refresh_token. What it does is during the first sign-in, the client gets a one-time code (from Google) which it hands to the server. The server uses this to talk to Google and get the access_token and refresh_token, confirming the user has authenticated themselves, and then sends something (usually a cookie) back to the client saying "ok, I've authenticated you. Here is how you keep authenticating yourself for the rest of our conversation."
That later action is pretty standard and is unrelated to oauth itself. The client and server then communicate as they always do - no oauth stuff is exchanged at all, you're relying on the cookie (or equivalent) to keep up the client-server authentication. The server continues to use the auth token and refresh token to talk to Google.
https://developers.google.com/identity/sign-in/web/server-side-flow I think is the best guide to this at the moment. Or at least it is the best one I can find at the moment. It has a good diagram, at least.
The key point is that you're exchanging the brilliantly named "code" with the server (what I was calling the "one-time code"). Once you have done that, the server authenticates you with Google - and it then has the access/refresh tokens and you communicate with the server without having to pass those.
Access tokens are short lived and only last for one hour this is not something you can extend.
What you need to do is take the refresh token and get a new access token.
example:
You take the refresh_token that you got from your initial request and HTTP Post it to: Note: grant_type=refresh_token
https://accounts.google.com/o/oauth2/token
client_id={ClientId}.apps.googleusercontent.com&client_secret={ClientSecret}&refresh_token=1/ffYmfI0sjR54Ft9oupubLzrJhD1hZS5tWQcyAvNECCA&grant_type=refresh_token
response
{
"access_token" : "ya29.1.AADtN_XK16As2ZHlScqOxGtntIlevNcasMSPwGiE3pe5ANZfrmJTcsI3ZtAjv4sDrPDRnQ",
"token_type" : "Bearer",
"expires_in" : 3600
}