How to generate expiration time for refresh token? - node.js

I need to generate the expiration time for refresh token, refresh token should expires in 200 days, how to generate exp time for this? Is there any libraries? And what format should be? unix, maybe YYYY/MM/DD etc? Any options please, thank you!

You could use json web tokens and make use of the jsonwebtoken package.
https://www.npmjs.com/package/jsonwebtoken
Specifically, if you make use of the options.expiresIn value this will take care of the date calculations and logic for you. When using the verify() method it will fail if the token has expired.

Related

What is the advantage of using refreshToken together with accessToken?

I am doing a small login, but I am trying to do it in the best possible way, I was testing only with a token and saved it in the DB, then decrypted and compared with the token, if it was the same and it was not expired then it allowed access, otherwise he denied access. But they told me that the Token should not be stored in the BD and they recommended me to use a refreshToken in addition to the token (access token). As I have read, the advantage of using a refreshToken is not forcing the user to have to log in again once the access token expires, and in this case, the refreshToken if it should be saved in the BD as I understand, is this the only advantage? in addition I also read that the refreshToken should also expire, how would it be done in this case? you should have to add 3 columns to the table of each user (refreshToken, date of issue and expiration? another question I have is that I saw in a place that to know if the access token is valid they only decrypt it and if it is achieved decrypting means that it is valid, that is, there would be no need to compare if it is equal to the token generated by the backend? excuse so many questions, but no matter what I have read it has not been clear to me, or I do not know if the guides that I have found they are not entirely complete I am very grateful to anyone who can help me understand this better Thank you in advance Greetings!

requests-oauthlib auto refresh Bearer token in client credentials flow?

I'm using the python requests-oauthlib package to connect to the Microsoft Graph. I am using the OAuth 2.0 Client Credentials flow.
The following simplified code works perfectly fine:
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
client = BackendApplicationClient(client_id='myclientid')
token_url = "https://login.microsoftonline.com/mydomain.onmicrosoft.com/oauth2/v2.0/token"
msgraph = OAuth2Session(client=client)
msgraph.fetch_token(
token_url = token_url,
client_secret = 'myclientsecret',
scope='https://graph.microsoft.com/.default')
response = msgraph.get(
url="https://graph.microsoft.com/v1.0/users/user#mydomain.com/messages")
While this works, the Bearer access token in this case is only valid for 1 hour. The requests-oauthlib package has support for refreshing tokens but it seems limited to token types that come with separate refresh tokens. The client credentials flow as used with the Microsoft Graph only issues an access_token.
So my questions are:
Is there a way to make the requests-oauthlib refresh the token automatically in this use case or do I need to manually track the age of my token and explicitly refresh it as needed?
I'm not wedded to requests-oauthlib so if there is a better library that accomplishes the auto-refreshing I'd be interested in using it.
This behavior is by design (and aligns with the OAuth spec). The only OAuth grants that support Refresh Tokens are Authorization Code and Resource Owner Password Credentials. The Implicit and Client Credentials grants only return an Access Token.
More importantly, since the Client Credentials flow isn't interactive, there is no need for Refresh Tokens. You simply request a new token when the old one expires.
As far as I can tell, there is still no built-in way to do this automatically using requests-oauthlib. There is a ticket about it on their GitHub with a couple of different ideas on how to do it, but nothing out of the box: https://github.com/requests/requests-oauthlib/issues/260
I know this is an old question, but it seems unanswered, so please allow me to give it a try.
My initial answer was:
I dare make the hypothesis, reading your mention of lack of refresh token, that you did not add offline_access in your requested scope - if you want it to be part of the answer from the Microsoft authentication service, you have to (please refer to https://learn.microsoft.com/en-us/graph/auth-v2-user#token-response and the various pages around for more details).
which was indeed totally irrelevant for the scenario used, as commented by Mark, and also clearly stated in https://learn.microsoft.com/en-us/azure/active-directory/fundamentals/resilience-daemon-app#cache-and-store-tokens:
It is important that applications use the "expires_in" property to determine the lifespan of the token.
So as an answer to your question 2., the above link also suggests the use of MSAL (MS Authentication Library):
MSAL implements and follows [best practices for caching and storing tokens] automatically.
what the why use MSAL wiki page seems to confirm:
It also adds value by [...] maintaining a token cache and refreshes tokens for you when they are close to expire. You don't need to handle expiration on your own.
For your question 1., I indeed did not find a standard way in requests-oauthlib to do so, either.
In this kind of situation, I usually don't monitor the age of the token, but just catch the 401 return code and fetch a new token.
To do so, I found suitable to tweak the first example of the Requests-OAuthlib - OAuth 2 Workflow - refreshing tokens section, replacing their call to refresh_token(refresh_url, **extra) by a new call to fetch_token().
What I usually use in order to avoid repeating the try...except... code piece, is to put it in a wrapper decorator (got a good inspiration in https://realpython.com/primer-on-python-decorators/#a-few-real-world-examples ) around my API-calling functions / methods.
Hope this time it helps more...

How to make a Single Use JWT

I am currently making a "forgot password" feature for my project. I'm attaching a JWT to the end of the reset password link that expires after 10 minutes. But I also want that link to only be used once (right after they reset their password). At first I figured I would just update the token expiration once they update their password (stupid) but once I did that, I realized that the token wouldn't update their url or the url in their email! So I'm just wondering if anybody knows of a way to create a single use JWT. Hopefully I gave enough information on what I'm looking for. If not, feel free to ask me to expound. Thanks in advance!
You could store the date/time of the last time a password change was made by the user in the db with their record. If the last password change time/date is greater than the time in which the token was created return false for the function. Sure you have to add a little logic but it shouldn't be difficult or extensive. There are better ways to do this which involve refresh tokens and so forth but this seems like a simple fix given the problem.

Generate SharedAccessSignature for one time use

Is it possible to generate a SharedAccessKey which expires after the first request rather than after a certain amount of time?
No, it's not possible. You would need some mechanism of your own to track the usage of shared access signature.

How to get the expiration timestamp of a session?

I'm using Node.JS and Express web framework, I need to work with Sessions.
I would get the expiration timestamp of the session, is this possible?
I would like to know when(timestamp format) the session expires.
Thank you!
From the official Connect docs, session middleware page (Express uses Connect internally):
Session#maxAge
Alternatively req.session.cookie.maxAge will return the time remaining
in milliseconds, which we may also re-assign a new value to adjust the
.expires property appropriately. The following are essentially
equivalent
So req.session.cookie.maxAge is what you're looking for.

Resources