I need to access a REST API using a token.
I am able to create a token that expires in 1 hour using one endpoint and then use that token to fetch some data at another endpoint.
I need to call the second endpoint multiple times every day and I could just create a token and then fetch the data each time, but that feels silly so I wonder what would be the right way to do this.
Should I be storing the token and the time of expiration and then reusing it until I know it's expired before I get a new token or how should I go about doing this? The only tokens I've used before are ones that don't expire, so I'm not really sure how to do this.
I would implement the Pseudocode logic below:
1/a/ Chek if token != Null? If true go to 3/
1/b/ If false, token==Null, go to 2/
2/ getToken() {make a resquest for a new token}, call 3/ after successfully retrieving a new token.
3/ queryAPI(token) {query the REST API}. If the token is expired you will get error 401 (sometimes 400 or 403 when people fail to send back the right error code, test it with your API), using a try catch, purge (delete) the current token and then go to 2/. If code 200 go to 4/
4/ ???
5/ profit
This way you do not need to check yourself if the token is expired, the API Endpoint will tell you
Related
I am new to JWTs and I have a question about it.
I have a web app with React, Node.js, express, using axios for ajax calls and npm jsonwebtokens for the access tokens.
I read a lot about JWT access tokens and refresh tokens but still one thing is not clear to me.
let's say a user logged in, got his access token and a refresh token, the access token will expire in 15 minutes.
What is the best way to go about it ?
set a timeout that will execute an API call to get a new access token after 15 minutes (let's say 14.5 minutes to be on the safe side)
set an interceptor that will check if the token is still valid and if not first get a new token and then continue with the request
is there another way I didn't considered?
If number 1 is the best way how do I handle a page refresh? the way I have it setup right now is when a user is logging in the login function calls a _refreshCountDown function that:
counts the time until the token expiration - with a setTimeout function
execute the refresh_token API call
call it self back again to start a new countdown based on the new expiration time
now if a user refreshes the page the login function is not being called therefore the _refreshCountDown is never being called.
how would you have handle this scenario?
will appreciate any answer
thanks :)
I'm building a react native app which uses the spotify web api. I'm using the authorization code flow to authorize a user. First I get a authorization code which can be used to obtain an access token and a refresh token. Everything works!
The problem is: an access token is only valid for a limited amount of time. That's where the refresh token comes in. I understand this concept, but I'm breaking my head about how to implement this.
Let's say a users opens the app, requests an access token and uses this for some time. Then, the user closes the app. After 15 minutes, the users opens the app again. The access token has now expired, so I need to request a new access token.
I've come op with several "solutions". Can someone point me to the correct solution?
Solution 1:
Every time the user opens the app, I request a new access token and use this. Problem: when the user uses the app longer than the valid time of the access token, I won't work anymore.
Solution 2:
I use the access token that's stored in the secure storage on every request. When a request comes back with 'access token invalid' (I don't know the exact error code but you guys know what I mean), I request a new access token with the stored refresh token, and then I send the previous command again (with the new access token). But my question here is: can I use some kind of "wrapper function" which checks the response of the request, and if the response is "access token invalid", it automatically requests a new access token and runs the previous request again.
I think certainly correct solution is solution 2,and i think its clear enough.
and for using solution 2 you need somthing like wrapper function,yes its intelligently.
so you should use interceptor:
what is interceptor ?
You can intercept requests or responses before they are handled by then or catch.
in link below there is a good example of implementing refresh token in axios interceptor:
https://gist.github.com/Godofbrowser/bf118322301af3fc334437c683887c5f
I agree that Solution 2 is the best, each time you do a request you can check to see if the Access Token has expired, and if it has then you can request a new Access Token using the Refresh Token as you mentioned and then make your request, in my own project I do this in a FormatRequestHeadersAsync method which calls a CheckAndRenewTokenAsync method where I perform the following check, here shown in C#:
if(AccessToken?.Refresh != null && (AccessToken.Expiration < DateTime.UtcNow))
{
AccessToken = await GetRefreshTokenAsync(
AccessToken.Refresh,
AccessToken.TokenType,
cancellationToken);
}
You can store the Access Token and the Refresh Token and then use something similar to this before you make each request to the API this will refresh your token and then you can store the new Access Token and the existing Refresh Token.
I have a RESTful API which will be users will reach via a set of web/mobile clients, and I am trying to figure out how to handle token auth. My understanding is that traditional token auth works as follows:
User auths by providing user/pass, receives back a token and expiration
Until , token is passed with every request
Upon expiration, a new token is requested (either by providing a separate 'refresh' token or just by re-authenticating with user/pass)
Is there a good reason not to generate a new token with each request? That is: an initial token is requested via user/pass. This token is passed with the first API request, which returns the content of the api response plus a new token which must be passed with the following request... The advantage to this approach would be that each request (action) the user takes 'resets' the expiration of the token auth such that the token expiration time basically becomes the period of time the user can be inactive without being logged out. Is there a good reason not to use this approach? The approach laid out above seems more commonplace (which is why I ask).
Finally, one only slightly related question. What stops someone who is watching the network from grabbing the token from the user? In particular in the first scheme, it seems easy to do (in the second method, you would need to capture the incoming request and then quickly get the next token before the user does).
From what I read is that you want a sliding window in which a user is authenticated. Every new request within the expiry window prolongs the session.
If I understand that correctly I would suggest an alternate approach; every time a request is successfully authenticated update your store in which you have your tokens and update the expiration time.
This way you don't have to bother your users with all the hassle of grabbing the new token every single time.
So, yes, there's a good reason not to do that: it's not necessary for your use case and only annoys the user.
With the above approach I assume that you have a store (database) in which you keep your tokens + an expiration date.
So the process is this:
The user provides username + password
Create record in store
Give user the token
Update store every time a successful request is made
On a related note; don't give the users the expiration date. That's fine when using cookies for example but that is merely useful as an additional security measure.
On your slightly related question; nothing stops anyone from grabbing the token if you don't use TLS/SSL/HTTPS. Always use TLS (which is SSL, which is HTTPS, more or less).
In OnLogin, Access token is valid for 10 hours and Refresh token is valid for 45 days.
I want to generate a new tokens(Refresh +Access Token) after 9.59hours.
My Question:
What will happen to the refresh token.Will it ever expire as I am generating the tokens(Refresh + Access token) for every 10 hours?
What is the best approach? Should I be refreshing the token or generating a new token for every 10 hours.
What can be done if the rate limit of 5000 is crossed with in an hour. Please suggest any alternatives.
Any suggestions or comments
Nope. Refresh token lifespan is measured from when it gets created. If you create a new one via refresh it'll 'live' for 45 days. The allows you to hold on to the tokens and still be able to make a new access (and refresh) token even if you haven't used them for a long while.
Some folks choose to simply use the generate token call and use the clientID/Secret to constantly generate a new access token. But this is not as secure as using the access token to make calls until you get a response that it's expired, and then use the refresh token (and refresh token call) to get a new access / refresh pair. The minimizes the chances that your secret/clientID will ever get leaked.
Once you've exceeded 5000 / hour you're done for the hour. I'm curious what scenario you have that needs more calls than this.
This number can be raised for certain extraordinary circumstances (You're a giant customer with a big account) but that's between you and your customer service contact.
I am a fair way through implementing an actionscript OAuth library which I am initially testing with Google's Drive Api.
I know how you are supposed to refresh an access token using your refresh token but my question is how do I test it?
How do I make my access_token expire so that I test my code that catches the error, attempts a refresh and then re-loads the initial request? If I can only do this once a week (or however often they expire) it's going to take a while to get it right!
Thanks
If you're looking to test your code, you don't actually need to invalidate or expire the access token. Simply make a (say) Drive call with a null access token and you will receive the same 401 response that you would have got with an expired access token.
Well, judging by the lack of responses to this question I am assuming that there is no way to do this.
This page:
https://developers.google.com/youtube/v3/guides/authentication#installed-apps
describes how to revoke an access or refresh token by using this url:
https://accounts.google.com/o/oauth2/revoke?token={token}
but then says:
The specified token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token is also revoked.
So if you just want to revoke an access token you aren't able to.
I think the only solution is to wait for the access token to expire (seems to take an hour) then go about testing your app.
I'll be very happy if anyone tells me a faster way to make the token expire.
I handle this testing by simply making note of an expired access_token. Then when I need to test how my app deals with an expired token I simply give the app that expired token to work with. This way, for example, I can test that requests with an expired token will fail as expected.
The easiest way of doing it is using the OAuth Playground 2.0
https://developers.google.com/oauthplayground/
In step 2 especially, you can try refreshing your access token with a refresh token.
Additionally, in the setting (the gear icon), you can set up your own OAuth Credentials to test it out for your own API project.
Im using nodemailer. When setting the options for the transporter object, you can specify an 'expires' time. There isn't any documentation I found on that option but I'm sure you can figure it out. :)
I haven't found a way to shorten the expiration time on an access token either.
In fact you can't even generate another refresh_token unless you revoke access. I don't think you can generate another refresh_token even if you let the access token expire, although I have to wait an hour to test this.
I did find out that if you send the refresh_token and the authorization token is still active, you just get the same live token back although the expiration time is reset.