jimt
jimt

Reputation: 2010

iOS authentication for file upload?

I'm struggling to figure out how to use my Box authentication tokens to use the Box API. I've built the authentication flow into my app so that I can save away the relevant pieces (access token, refresh token, etc.) to the Keychain. The issue I'm having is that whenever I re-open the app, I can't seem to find an appropriate way to set up my BoxOAuth2Session or whatever to re-use the saved tokens to upload files to Box. Currently, I'm recreating the BoxOAuth2Session with my clientID and secret, and manually setting the accessToken, refreshToken, etc. values on that session. I create a BoxFilesResourceManager, attach this BoxOAuth2Session, and upload a file with uploadFileWithInputStream. This request always fails with a 401. The only way I have been able to upload files to Box is immediately following the login step using the [BoxSDK sharedSDK].filesManager. What is the expected workflow for re-creating the OAuth state to access the API?

Upvotes: 2

Views: 1062

Answers (1)

Ryan Lopopolo
Ryan Lopopolo

Reputation: 231

A BoxOAuth2Session is bound to an SDK instance. When you access the [BoxSDK sharedSDK] singleton, you are using an instance of the SDK that is already wired up with its own BoxOAuth2Session and manager instances. In normal usage, we recommend using the sharedSDK singleton, so you should manipulate the BoxOAuth2Session attached to this SDK.

One way to do this is to attempt to load a refresh token from the keychain and set the refreshToken property on the OAuth2Session.

[BoxSDK sharedSDK].OAuth2Session.clientID = @"YOUR_CLIENT_ID";
[BoxSDK sharedSDK].OAuth2Session.clientSecret = @"YOUR_CLIENT_SECRET";

// set up stored OAuth2 refresh token
self.keychain = [[KeychainItemWrapper alloc] initWithIdentifier:REFRESH_TOKEN_KEY accessGroup:nil];

id storedRefreshToken = [self.keychain objectForKey:(__bridge id)kSecValueData];
if (storedRefreshToken)
{
    [BoxSDK sharedSDK].OAuth2Session.refreshToken = storedRefreshToken;
}

The SDK will automatically refresh the OAuth2 session and acquire a new access token and refresh token on the next API call, so long as the refresh token has not been revoked and is not expired. You may wish to manually trigger a heartbeat call to force a refresh.

We've put together a sample app that demonstrates how to store and load refresh tokens using the keychain.

As a side note, we do not recommend storing the access token on the device since this token is a bearer token; losing this token could allow Mallory to impersonate your app's users.

Upvotes: 4

Related Questions