Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto update/refresh of OAuth2 access tokens #10112

Closed
semangard opened this issue Jul 12, 2021 · 36 comments
Closed

Auto update/refresh of OAuth2 access tokens #10112

semangard opened this issue Jul 12, 2021 · 36 comments

Comments

@semangard
Copy link

semangard commented Jul 12, 2021

Problem
As recommanded by security best pratices,
our access tokens are <= 5 min
BUT this means each 5 min we have to get a new access token and ask postman to use the new one

Solution wished
Postman gets 2 tokens:

  • the access token
  • the refresh token
    Postman should refresh automatically the access token thanks to the refresh token
    Postman should use the latest access token retrieved by this mean

image

Alternative
Let the tokens and additional infos like 'expires_in' been available through var envs in order to script the refresh mecanism.

Additional wish
I do not see why I have to click on "Use token" if there is only one token available or not expired

@semangard
Copy link
Author

semangard commented Jul 12, 2021

It seems Insomnia has this feature
https://insomnia.rest/blog/oauth2-github-api
image

Confirmed by brightcove
https://apis.support.brightcove.com/general/use-insomnia-api-requests.html
image

@semangard
Copy link
Author

Hi @chrisdeso : do you have any idea of ETA ?

@giridharvc7
Copy link

This is on our roadmap, will share ETAs soon.

@scollovati
Copy link

I am an Insomnia user and the lack of this feature is astonishing. Actually, I have found that this was causing some of my automated tests to fail due to this error.

@TribuneX
Copy link

We also moved to the OAuth2 workflow. This feature would save us a huge amount of time each day!

@karlisl
Copy link

karlisl commented Aug 18, 2021

This is on our roadmap, will share ETAs soon.

@giridharvc7 What's the ETA on getting an ETA? If you don't want to build the whole flow at least expose the stored values.

@semangard semangard changed the title Auto update of OAuth2 access tokens Auto updat/refresh of OAuth2 access tokens Aug 18, 2021
@semangard semangard changed the title Auto updat/refresh of OAuth2 access tokens Auto update/refresh of OAuth2 access tokens Aug 18, 2021
@giridharvc7
Copy link

We expect to get this out by Q4, this year :)

@semangard
Copy link
Author

@giridharvc7: do you have any news ?

@semangard
Copy link
Author

@giridharvc7: do you have any news ?

@JoanChirinos
Copy link

@giridharvc7 Any updates on this issue?

@shubhbhargav
Copy link

@semangard @JoanChirinos Really appreciate the patience folks. We are expecting some delay in getting this done. The tentative timeline is mid-March. We will share explicit timelines within the next 2-3 weeks.

@shubhbhargav shubhbhargav self-assigned this Jan 24, 2022
@savage-alex
Copy link

We have a pre-request script for access token refresh when using authcodeflow if anyone is interested

@semangard
Copy link
Author

@shubhbhargav : do you have any news ?

@shubhbhargav
Copy link

@semangard This is definitely on our radar. We are planning to release the first set of changes by mid-April :fingers-crossed: :)

@joaquin-rossi
Copy link

We have a pre-request script for access token refresh when using authcodeflow if anyone is interested

do you mind posting it here?

@savage-alex
Copy link

@joaquin-rossi, as requested. As below this was a mod from the lovely people at Box's postman collection. Props to them. I just modded it a little to fit my needs. It requires a refresh token to run but once you have that, it checks before each request if the access token is expired and if it is, then gets a new one.

/**
 * Pre-request script ran before every API request.
 *
 * Used to notify users that their access token has expired
 * 
 * Based on work by box.com: https://developer.box.com/guides/tooling/postman/
 * 
 * If you are using a flow that required clientSecret then uncomment those sections and add an environmental variable
 */

// Determine if accessTokenExpiry exists in the environment
const expiresAt = pm.environment.get('accessTokenExpiry')
if (!expiresAt) {
    console.log('accessTokenExpiry does not exist, creating a new environment variable and setting it to an old expired date time')
    pm.environment.set('accessTokenExpiry', Number(1637945308569))
}
// Determine if the Access Token has expired
const expired = Date.now() > Number(expiresAt)
// Determine if the user has auto-refresh enabled
if (!pm.environment.get('enableAutoRefresh')) {
    console.log('enableAuoRefresh does not exist, creating a new environment variable and setting it to false')
    pm.environment.set('enableAutoRefresh', false)
}

const autoRefresh = String(pm.environment.get('enableAutoRefresh')) === 'true'
// Determine if we have all the client credentials needed in the environment
const hasClientId = String(pm.environment.get('clientId')).length > 0
const hasRefreshToken = String(pm.environment.get('refreshToken')).length > 0
const hasAllCredentials = hasClientId && hasRefreshToken //&& hasClientSecret

// Determine if autoRefresh is enabled and only continue if it is.
if (!autoRefresh) {
    console.log('Enable auto refresh is disabled')
}
// If the access token expired and auto refresh has been set, use the refresh
// token to create a new access token
else if (expired && autoRefresh && hasAllCredentials) {
    console.log('All prerequisites are met so getting new access and refresh tokens')
    // Send a new API request to refresh the access token
    pm.sendRequest({
        url: pm.environment.get('tokenUrl'),
        method: 'POST',
        headers: { 'Content-Type': 'Content-Type: application/x-www-form-urlencoded' },
        body: {
            mode: 'urlencoded',
            urlencoded: [
                { key: 'client_id', value: pm.environment.get('clientId'), disabled: false },
                //{ key: 'client_secret', value: pm.environment.get('clientSecret'), disabled: false },
                { key: 'refresh_token', value: pm.environment.get('refreshToken'), disabled: false },
                { key: 'grant_type', value: 'refresh_token', disabled: false }
            ]
        }
    }, function (error, response) {
        if (error || response.json().error) {
            // If an error occurred, log the error and raise a message to the user.
            console.log('Could not refresh the access token')
            console.log(error)
            console.log(response.json())
            throw new Error('Could not refresh the access token. Check the console for more details.')
        } else {
            // Otherwise, fetch the new access token and store it
            const data = response.json()

            // Determine when this token is set to expire at
            const newAccessTokenExpiresAt = Date.now() + data.expires_in * 1000
            // Store the new variables in the environment
            pm.environment.set('accessToken', data.access_token)
            pm.environment.set('refreshToken', data.refresh_token)
            pm.environment.set('accessTokenExpiry', newAccessTokenExpiresAt)
            console.log('New access and refresh tokens stored successfully')
        }
    })
}
else if (expired) {
    // Otherwise, throw a message to the user if the access token expired.
    throw new Error('Refresh token expired. Please generate a new refresh token via the authentications section at the top of the collection and save it into the environment and try again.')
}

To use it, setup the collection with OAuth2 auth code flow security and using postmans normal UI generate a new access token AND refresh token --< this is what it needs, then copy the refresh token into the environment variable and it will then hand that in to create a new access and refresh token pair.

@savage-alex
Copy link

We have a pre-request script for access token refresh when using authcodeflow if anyone is interested

do you mind posting it here?

Your welcome to fork the public workspace if that's preferred https://www.postman.com/universal-escape-252485/workspace/oauth2-0-auth-code-flow-token-refresher

@savage-alex
Copy link

Cool write up about Postman's current OAuth2.0 Implementation https://dev.to/oneadvanced/oauth-20-authorization-code-grant-with-postman-part-1-5238

@Smitzel
Copy link

Smitzel commented Apr 8, 2022

Cool write up about Postman's current OAuth2.0 Implementation https://dev.to/oneadvanced/oauth-20-authorization-code-grant-with-postman-part-1-5238

Great setup Alex,
Still getting this error:
error: "invalid_grant"

@savage-alex
Copy link

@Smitzel is refresh grant enabled on the provider you are calling?

@Smitzel
Copy link

Smitzel commented Apr 8, 2022

@Smitzel is refresh grant enabled on the provider you are calling?

Will check it, thanks

@ebuter9292
Copy link

Is there a new ETA available on this feature?

@Xhoii
Copy link

Xhoii commented May 10, 2022

Any news ?

@ybussieresbreezeway
Copy link

hey hey

@giridharvc7
Copy link

We have picked up this feature. We will post updates as we get closer to release.
Also this is a duplicate of #2452 , closing the ticket here - please use the other issue.

@RashaBadri
Copy link

i have same issue the toggle button is disabled (wind 10, postman version 10.10.6)
and even the code mentioned above not working
image

@mike-loux-planview
Copy link

mike-loux-planview commented Feb 21, 2023

I have the same issue as RashaBadri.
When I hover over the toggle, I get the message: "Refresh token is not present. Generate a new token to refresh it automatically on expire."
Getting a new token doesn't change anything.
The goggles, they do nothing.
Also, I am not even seeing the "Use Token Type" drop down at all.
Also not seeing an expiry date on the token like some users are seeing. But I am able to remove expired tokens in the manage screen, so Postman seems to know when a token is expired or not...

@abhijeetborole
Copy link
Member

@RashaBadri @mike-loux-planview Could you verify that you've received a valid refresh_token with your token response? You could check this in the Manage Tokens section -> Open the token dropdown and select Manage Tokens.

Screenshot 2023-02-22 at 9 30 46 AM

Screenshot 2023-02-22 at 9 31 03 AM

@mike-loux-planview The Use Token Type dropdown is available when you have a valid id_token present. We default to using access_token when this is not present.

Screenshot 2023-02-22 at 9 37 41 AM

@RashaBadri
Copy link

@RashaBadri @mike-loux-planview Could you verify that you've received a valid refresh_token with your token response? You could check this in the Manage Tokens section -> Open the token dropdown and select Manage Tokens.

Screenshot 2023-02-22 at 9 30 46 AM Screenshot 2023-02-22 at 9 31 03 AM

@mike-loux-planview The Use Token Type dropdown is available when you have a valid id_token present. We default to using access_token when this is not present.

Screenshot 2023-02-22 at 9 37 41 AM

yes id_token exist, but the toggle is not enabled
image

@mike-loux-planview
Copy link

OK, it does require a refresh token, then. One of the comments I saw on the demo video seemed to imply that it didn't, and that it would just resend the original request to get a new token with the existing client creds. So that's my fault for misunderstanding.

That being said, it would be really cool if Postman could do that as well. The app I'm using the most doesn't issue refresh tokens, and while I can write a pre-request script to check and get a new token if necessary, if I didn't have to, that would be a nice time-saver.

@bodograumann
Copy link

That is not how OAuth usually works @mike-loux-planview .
Postman has no access to your credentials. Instead it redirects you to your auth providers login page and gives it a return adress to which the jwt should be send after your login has succeeded.
So there is no way to just "repeat the process" without involving you as a user.

@mike-loux-planview
Copy link

Oh well, it would have been nice. The implementation we use doesn't have a login page or a return address - this is purely for server-to-server REST requests. I'll just write the pre-request script (or just continue manually grabbing a new token when I need it, since I'm lazy). At least it is good to know that if I do come across implementations that have refresh tokens, it will be sorted.

@xjrcode
Copy link

xjrcode commented Mar 28, 2023

I don't know how or where Insomnia get the refresh_token but its completely transparent for me. In Postman the auto-renew checkbox is disabled because the response don't include any refresh_token or id_token

Can I help in some way?

@patricksindelka
Copy link

According to OAuth2 specifications, you will not get a refresh token if the grant type is Client Credentials. Then you just have to repeat the call to retrieve a new access token when yours is expired.
Unfortunately, Postman still does not support doing that automatically, it can only refresh tokens when there is an access token. Would be very useful if they would add that functionality.
Now the only way to auto-refresh your tokens in such a scenario is creating a pre-request script and move all the OAuth logic to that script.

@mike-loux-planview
Copy link

Yup. Which is what I have done for about half of the API's I work with on a regular basis - pre-request script that checks a token's expiry, then gets a new token if needed.
The other half, I just do manually via the dialog - especially the API I do active development in, as the server uses a random key that is generated each time it starts up, so any unexpired tokens from a previous session won't work anyway. Long story - not my decision - but it is what it is.

@niko-vulic
Copy link

Why was this closed? This isn't implemented

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests