Reputation: 1520
I have been working with the IAuthorizationState (AuthorizationState) and the WebServerClient and I am trying to figure out the right way of persisting the authorization state information such that on retrieval the framework can make an optimal decision on what call needs to be made to get the access token I need for a web service call.
Assuming I am starting from scratch and have no tokens persisted in the DB yet, I go through the following steps:
WebServerClient.PrepareRequestUserAuthorization
- user is sent off to google. The url contains the offline parameter for a refresh tokenProcessUserAuthorization
- I get the code parameter back (authorization code) from google and call to get the AccessToken and RefreshToken along with the expiration datesIf I now want to persist that, should I persist the entire object so the dates are persisted as well or will the two tokens be enough?
When a user performs another action that needs the authorization state information, I can now do a DB lookup to retrieve the token. Do I always need to call the RefreshAuthorization method after I have retrieved the tokens or should I perform my own logic to see if the dates are past their expiration (assuming i persisted those too)?
UPDATE 1:
I ended up persisting the dates in the DB so the IAuthorizationState can be fully restored to its last state. I then call
client.RefreshAuthorization(auth, TimeSpan.FromSeconds(MinRefreshTimespanInSec));
which returns true if the token ends up being refreshed or false if it is still valid and doesn't need to be refreshed. The variable auth is the authorization state restored from the DB.
Upvotes: 2
Views: 2538
Reputation: 86937
At a minimum, you'll need to store the two token, but I would also store the dates if you need to access any of the OAuth services.
So .. why store the dates? well, if you can use the date data as a check BEFORE you try and access a service, you can redirect the user to re-auth against the provider proactively .. otherwise, you will try and access a service (eg. post a tweet) which will give you an error (access expired or whatever)... which means you need to handle that error case AND THEN redirect the user to auth again.
Of course, if you never use any of those services (eg. you've authenticated against Twitter but will NEVER use any Twitter services), why bother saving any of that data? You're not going to use it after all.
BONUS TIP: Simple Authentication might be an easier way to do (simple) OAuth for your .NET application.
Upvotes: 1
Reputation: 3070
If you store the access token expiration date, you know when is time to exchange a refresh token for a new access token: so you don't have to bother final user with an additional round-trip to the oauth2 provider.
Upvotes: 1