I’m working with a REST API that returns a 401 if my authorization token has expired. When I receive a 401, I’d like to run my authentication logic, retrieve a new token and then retry my original call. What’s the best way to do this.
Right now, I have an Authenticator class that “knows” how to authenticate with the API. The rest of the data access logic lives in a Repository object. The Repository object has the responsibility of sending requests to the API to retrieve information, using the information stored in the Authenticator.
An example of this is Repository.List() [It’s not really static, just writing it this way for brevity). Conceptually, this is what List() should do.
- Try to connect to API and get a list of items
- If 401 error, re-authenticate and try again
- Return the list of items or throw an exception
This pattern will be used for all of my methods in all of my repositories, so I’d like a delegate or something that I could use with all of the API calls.
Any ideas?
Thanks,
Greg
I came up with a solution that is working well.
I created a static method that accepts two arguments, a Func and a reference to my
Authentication object. The Authentication object can re-authenticate, and holds the auth info for making API calls. I used a ref because I didn’t want multiple instances of an Authenticator for one account existing with different auth tokens, but I needed to be able to support multiple accounts at the same time, so I couldn’t make it static.
I then have different classes for requesting data from the API. Here is what one of them might look like, where _authenticator is passed into the class when the class is instantiated.
The beauty is that I can pass in whatever logic I want to ReathenticateOn401, and it will attempt to call the method, and then reauthenticate if a 401 is received. Otherwise, it will succeed or throw an exception that I can then handle.