Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an access token without Box’s authorization page

Tags:

box-api

I have been granted access(collaborate) in a folder. What I need is to access the folder daily and fetch files from it. Right now the developer token I generate expires in 1 hour. Is there a way I can get the authorization code without the first leg, which requires a user interface. This way I can refresh the access toke whenever I fetch files.

like image 925
xiao Avatar asked Feb 06 '14 20:02

xiao


2 Answers

You should be able to refresh the token without getting an authorization code. When the access token is sent back, a refresh token is also issued to you.

{
    "access_token": "T9cE5asGnuyYCCqIZFoWjFHvNbvVqHjl",
    "expires_in": 3600,
    "restricted_to": [],
    "token_type": "bearer",
    "refresh_token": "J7rxTiWOHMoSC1isKZKBZWizoRXjkQzig5C6jFgCVJ9bUnsUfGMinKBDLZWP9BgR"
}

You should store this refresh token somewhere secure (keychain, encrypted datastore, something similar) and use it to refresh the session when it expires.

You can tell the session is expired when you receive a 401 Unauthorized response from Box for any API request AND you see a WWW-Authenticate header with the value Bearer realm=.

The flow should look something like:

1) Log into Box and get an authorization code

2) Exchange the authorization code for an ACCESS TOKEN and REFRESH TOKEN pair (this only needs to be done once!)

3) Store the refresh token

4) Begin making requests with the API

5) When a 401 Unauthorized is received with a WWW-Authenticate header in an API response, issue a www-form-urlencoded POST request to Box like this:

curl https://www.box.com/api/oauth2/token \ -d 'grant_type=refresh_token&refresh_token={valid refresh token}&client_id={your_client_id}&client_secret={your_client_secret}' \ -X POST

If successful, you'll be issued a NEW access token AND refresh token pair. Store the new refresh token, swap out the old access token for the new one, and resume your API calls from your previous failed call.

Hope that helps!

like image 125
Skippy Ta Avatar answered Oct 26 '22 22:10

Skippy Ta


Found a nice package which answers my question. :) https://github.com/sookasa/box.py

like image 23
xiao Avatar answered Oct 26 '22 23:10

xiao