Quicksilver
Quicksilver

Reputation: 295

Is there a way to programmatically renew a Box refresh token?

I am coding a console c# app that will run on a daily basis on Windows 7. There is no user interaction.

The app simply uploads a CSV to Box, using OAuth2 and the latest API/SDK.

I'm hoping to eventually use an enterprise ID, but I'm doing this within a corporate site, and it's difficult to get permission to use it. So for now, I've simply created an app with my login, authorized the app, and manually received & stored my refresh token.

I am having trouble figuring out how to manage the refresh token in C#. I see some objects in java that make it look very easy, but I don't see corresponding C# objects? Do I have to manually re-authorize my application after 60 days using the Box login web page? If not, what do I need to do to detect that my refresh token has changed, and how do I retrieve the new one?

I'm also having some trouble because it seems like a lot of objects changed with the latest API, and whenever I search for code, it's from a couple years ago and it's now obsolete.

Upvotes: 0

Views: 1076

Answers (1)

Quicksilver
Quicksilver

Reputation: 295

I figured it out, though the solution seems kind of clugey.

Basically, you always have to be ready to create another auth session if necessary. You create one auth session, see if it's valid, and if it's not, create a second one that you use for real. You would test for this by trapping two events:

boxClient.Auth.SessionAuthenticated += Auth_SessionAuthenticated;
boxClient.Auth.SessionInvalidated += Auth_SessionInvalidated;

To me, this seems silly -- I'm running my app once / day, so I just want to refresh my tokens every time. So I always create two:

        var config = new BoxConfig(CLIENT_ID, CLIENT_SECRET, new Uri(RedirectURI));

        // Prior to this code snippet, I grabbed my starter access & refresh tokens from where I stored them in our db.
        var auth = new OAuthSession(InitialToken, RefreshToken, 3600, "bearer");
        var client = new BoxClient(config, auth);

        /// Try to refresh the access token
        var realAuth = await client.Auth.RefreshAccessTokenAsync(auth.AccessToken);
        /// Create the client again
        var realClient = new BoxClient(config, realAuth);

        //going to just log/update tokens every time. This only runs 1x / day, so should be no harm.
        LogNewTokens(realAuth.AccessToken, realAuth.RefreshToken);

And then I use "realClient" for the rest of the Box requests.

In retrospect, it would probably have been faster for me to just lift code for posting these requests directly to Box and parsing the JSON returned. I expected to have a nice wrapper object that would automatically update my tokens for me, connect, and make the new ones easily available. I think they could have done a better job with the C# SDK.

Upvotes: 1

Related Questions