Azure AD refresh token expire - azure

I have a multitenant web api project with microsoft azure integration. I connect to microsoft, get access token and refresh token and each time before access token expiration, I call api
POST https://login.microsoftonline.com/tenant/oauth2/v2.0/token
data in request is:
grant_type=refresh_token
refresh_token=xxxxxxxxxxx
client_id=xxxxxxxxxx
I get new access token and refresh token, and after an hour get new access token with the same api and last recieved refresh token. But after 24 hours somehow my refresh token expires, and I need to reconnect and enter my credentials again.
How to make my refresh token don't expire until i revoke it manually. I need somehow update refresh token timeout in background and save my integration always connected until i revoke it manually.
I need somehow organize this to stay connected always until manual revocation. Any solution?

There is a 24 hour limit to refresh tokens under certain conditions:
Refresh tokens sent to a redirect URI registered as spa expire after
24 hours. Additional refresh tokens acquired using the initial refresh
token carry over that expiration time, so apps must be prepared to
rerun the authorization code flow using an interactive authentication
to get a new refresh token every 24 hours. Users don't have to enter
their credentials and usually don't even see any related user
experience, just a reload of your application. The browser must visit
the log-in page in a top-level frame to show the login session. This
is due to privacy features in browsers that block third party cookies.
See: https://learn.microsoft.com/en-us/azure/active-directory/develop/refresh-tokens

Related

When should we refresh access token in frontend?

Let's say we have short-lived access token (15 minutes) and long-term refresh token (7 days).
When should we ask backend to refresh access token?
I see two options:
After user logs in we start a countdown to automatically refresh token one minute before access token expires.
We don't implement timer and we try to refresh access token ONLY if we get 401 response from backend.
In first option I see one advantage -
if access token and refresh token will expired AND user stays on the page, not taking any action, he also doesn't send any http request than the timer still works and user is logged out automatically.
In second option -
if access token and refresh token will expired user will be logged out ONLY if he will make some action on page for example: leave a page or make a http request.
If he will stay on page he won't be logged out automatically.
What is a better implementation on frontend than?
I would recommend option 2 as your default behavior, since it will give you a resilient app. Every OAuth client should do this, since 401s can sometimes also be received for infrastructure reasons in some setups, eg token signing certificate renewal.
Option 1 is an optimization, if you want to reduce 401 responses from APIs. However it can lead to incorrectly developed clients and APIs if you are not careful. Personally I never use it.
Note that an expires_in field is returned with the access token but there is no equivalent field for the refresh token, so the client cannot detect when the user session will expire unless you develop a custom solution.
When coding API calls it is recommended to do this, as in this sample code of mine:
When a 401 is received try a token refresh
On success retry the API call - once only
On failure redirect the user to authenticate again
Out of interest there is an online version of the above app that allows you to test OAuth expiry events to see how this behaves - see my Quick Start page

How to regenerate Refresh Token and Access Token on Resource Request?

I am trying implementing JWT Tokens(Access tokens and Refresh tokens), but I come to an issue on requesting a protected resource with an expired access token, while the refresh token is still valid.
I know that I should not use refresh tokens to request resources, refresh tokens should be used against authorization validators to revalidate/regenerate access tokens.
In my app, the User can log in by POST request with a valid credential to get Access token(exp. in 1min) and Refresh token(exp. in 10min.). Say now User making a request 30 sec later of login and sends both tokens, then tokens get checked and resource comes back. If now user makes a request after 2min and sends tokens, his access token is Invalid, in this scenario how can I proceed with the request and revalidate tokens.
I can think of middleware to validate and provide tokens and send that with the response, but is this the right approach?
Then I need to handle and restore tokens on the client-side for every response. Don't I?
Also, I do not want to prompt users to re-login. I am using Node and Express for Server and React on Client.
Here are your steps:
Try to login
Receive 401 from server when token is invalid
Request a new access token by making a new refresh request.
Set the new access token and refresh token
Retry original request
This has to be done on the client side because it is the audience that gets validated for authorization.
Usually we don't set the access token to expire every minute because the described process would add too much latency to the process.
Edit from #MComment:
5 min for access tokens and 30 min up to a few hours is what is generally recommended for respectively access and refresh tokens. Usually Authorization Servers offer "rolling refresh" - refresh token's expiration is renewed whenever you use it. This way a user stays logged in as long as they are actively using the website
You can update expired date of access token in every request, no need to regenerate token.
I think session time you set is not normal and recommended.
If you dont want user must re-login, make a forever refresh token, create a function in reactjs for re-generate access token by refresh token if it expired.
Revoke refresh token only when u want to logout from this client.

Does Azure ad refresh token for Confidential clients neve expire

In doc https://learn.microsoft.com/en-us/azure/active-directory/active-directory-configurable-token-lifetimes, it said:
Confidential clients are applications that can securely store a client
password (secret). They can prove that requests are coming from the
secured client application and not from a malicious actor. For
example, a web app is a confidential client because it can store a
client secret on the web server. It is not exposed. Because these
flows are more secure, the default lifetimes of refresh tokens issued
to these flows is until-revoked, cannot be changed by using policy,
and will not be revoked on voluntary password resets.
Now for my webAPI app, I should make sure refresh token neve expire.
My questions:
1.Does refresh token for Confidential clients neve expire until revoked?
2.When I use old refresh token to get new access token, server will return a new refresh token which is difference from old refresh token. Should I use new refresh token to replace old refresh token? Or is that both old and new refresh tokne will neve expire unitl revoke?
One critical piece of text in that documentation:
will not be revoked on voluntary password resets
So it means for confidential clients, refresh tokens are not revoked if the user changes their password.
However, I do not believe this applies to a reset done by an admin.
Whenever you use refresh tokens, you must be prepared for the case when the token does not work.
If your app has critical features depending on that access and cannot handle downtime for access to the data, you need to use application permissions.
There is this bit for the second question:
Refresh Token Max Inactive Time (issued for confidential clients) 90 days
So a refresh token which is not used for 90 days will no longer work.
I would replace the current refresh token with the new one always, and make sure to refresh the refresh tokens periodically if it is possible they don't get used.

How long is the refresh token valid?

On my localhost, I have authenticated my user and goten a Refresh Token and Access Token using Passportjs.
I am using Google's Official Node.js library to get the Google Analytics data and it all seems to work fine.
On this GitHub issue, Justin clearly mentions that the expiry is set by Google's APIs.
How long is the refresh_token valid and at what time do i have to authorize myself again?
This is more of an Oauth2 question then a Google Analytics question.
Access tokens on google servers are good for one hour.
The refresh token does not expire and you can use it as many times as you want to request a new access token.
You should still handle invalid refresh tokens in your code. The user can revoke your access via there Google account. You can have max 50 out standing refresh tokens before the first one starts working. If i authenticate your application you will be given a refresh token if i do it again you get another refresh token there can be max 50 of them outstanding.
If the refresh token does become invalid you should just request authentication from your user again. The library you are using should be handling refreshing the access token for you.

Azure AAD token expire issue with web app

We are using Azure AD authentication with a bootstrap MVC site.
Everything is fine and dandy - except we have an issue with the token timeout.
I have read multiple articles about the token lasting 1 hour before re-authenticating against Microsoft.
Our problem comes up when posting data.
Efter we enter a page with a post form on it - and this hours expires when on the page - the post data gets lost when posting the data. Everything points in the direction of the problem occurring when the site goes to get a fresh 1-hour token.
Has anyone here had experience with this or have any idea of how to get around this problem?
Not sure if this is the right way of doing things, but this is how we're handling this situation.
Basically when a user authenticates against Azure AD, you get 3 things back - Access Token (which expires after 60 minutes), Refresh Token and Token Expiry. What we do in our application is cache these three items.
Whenever we perform something that requires Access Token, we first check if the token has expired or not (by comparing the server date/time with the token expiry). If the token is not expired, we simply use that access token. However if the token is expired, we fetch new tokens using refresh token (fetching new tokens using refresh token will again return Access Token, Refresh Token and Token Expiry which we cache again in our application).

Resources