Django/Python + LinkedIn JSAPI <> oAuth Tokens

This past week I spent a little time working with LinkedIn’s JavaScript APIs.

The APIs themselves are quite powerful and easy to work with.  Complications arose when it came time to convert the temporary JSAPI tokens to their oAuth equivalents.

https://developer.linkedin.com/documents/exchange-jsapi-tokens-rest-api-oauth-tokens

First things first, LinkedIn only passes the JS API oAuth 2.0 token over an SSL connection.  Slighly annoying from a development perspective, as I wasn’t normally running SSL on my local Mac. That being said, getting nginx setup through homebrew was straight forward. It works fine with a self-signed certificate as well.

Once you have SSL setup

<script type="IN/Login" data-onAuth="onAuth" data-onLogout="onLogout"></script>
function onAuth() {            
   $.post("https://" + window.location.hostname + "/my-app/token-exchange");
}

After a successful LinkedIn authentication, the onAuth() function will be invoked and a POST made to your backend resource over SSL.

def token_exchange(request):
 oauth_token = None
oauth_secret = None
 if request.session.get('linkedin_oauth_token'):        
    oauth_token = request.session.get('linkedin_oauth_token')        
    oauth_secret = request.session.get('linkedin_oauth_secret')    
 else:        
    oauth_token = request.COOKIES.get('linkedin_oauth_%s' % settings.LINKEDIN_API_KEY)        
    oauth_token = urllib.unquote(oauth_token)        
    oauth_token = json.loads(oauth_token)

consumer_key = settings.LINKEDIN_API_KEY       
 consumer_secret = settings.LINKEDIN_SECRET_KEY        
 access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
 access_token = oauth_token.get('access_token')
consumer = oauth2.Consumer(             
    key=consumer_key,             
    secret=consumer_secret
 )
 client = oauth2.Client(consumer)
resp, content = client.request(access_token_url, "POST", body='xoauth_oauth2_access_token=%s' % access_token)       
 request_token = dict(urlparse.parse_qsl(content))        
 oauth_secret = request_token.get('oauth_token_secret')        
 oauth_token = request_token.get('oauth_token')
request.session['linkedin_oauth_token'] = oauth_token       
 request.session['linkedin_oauth_secret'] = oauth_secret

 

The code snippet above is a django view *that requires *oauth2.

And that’s it.  You’ve now successfully converted JS API tokens to oAuth tokens in a Python/Django environment.