C# – How to make sure I always have an API token

apiasp.netauthorizationcnet

I am writing an API, in that API I sometimes need to make a call to another, remote API. This remote API needs an authorization token, which it gives if you call an appropriate method (for example, /api/GetAuthToken?user=user&pass=pass, where user and pass are hardcoded or passed to my API via settings file). Then you can use this token to call other methods, which I actually need. This token is valid for some time. If it expires, API calls return 401 – not authorized. My question is – what is the best way to make sure that I always have a "fresh", working token and always replace it when it expires? An API object is singleton, it may receive concurrent requests.

Best Answer

The simplest and most straightforward solution (therefore best in my opinion) would be to have a helper method that gets the api parameters as its parameters and simply calls the api with these. Then it checks the return code, with the condition that if 401 is recieved, it calls GetAuthToken then calls the api again.

Related Topic