0

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.

2
  • Have you looked at OAuth2? Commented Feb 16, 2021 at 3:50
  • Yes a bit. I understand how the basics of how it should work and I know how to get it to work for whatever I need. Just didn't want to do something incorrectly (such as creating tokens every time instead of refreshing them or something of that sort) Commented Feb 16, 2021 at 19:00

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

8 Comments

Ok, thanks. That seems easy enough. And I guess it makes sense, still feels a bit strange to have to just try to use it until you get an error. Is this the "right way" to do it or just an easy way that works?
I would say an easy way that works and also the right way if you are not limited on the number of query you can make to the API endpoint
Note that in the case that the endpoint takes a long time to return error 401 you might want to implement a check on the token expiration by comparing with current timestamp, but then you have to be careful with the timezone.
And just to be sure, I'm not usually expected to do anything to clean up old tokens, they just expire and disappear from the system, right? (I don't think I'm able to do remove them anyway, but just thought I'd ask in case I'm mistaken)
It depends on the auth server issuing your token, if they have good security policy they should expire in at most 24h, but I can't guarantee this, it depends on their settings
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.