cerrina
cerrina

Reputation: 553

Refresh LinkedIn token with omniauth before expiration

I have a Rails (3.2.11) application that allows users to post updates to their LinkedIn profiles. I'm currently using the omniauth-linkedin gem to capture the initial user authentication and the linkedin gem to post the updates. The problem I'm having is that LinkedIn access tokens expire after 60 days, but according to their documentation a token can be refreshed prior to expiration without a user having to reauthorize the application.

I've looked at the LinkedIn Tips and Tricks, Authentication Overview, and tons of posts on StackOverflow - this, this, and this being just a couple of examples - and I still can't find any answers.

After a user authorizes the app (via omniauth-linkedin), I save the access_token and secret returned to me from LinkedIn. I need to figure out how I can use the still-valid access_token to refresh it and extend the expiration date another 60 days.

I've tried using the authenticate endpoint from LinkedIn (where tokens.access_token is the currently valid token):

url = "https//www.linkedin.com/uas/oauth/authenticate?oauth_token=" + tokens.access_token
result = RestClient.post(url, {oauth_callback: "http://localhost:3000/users/auth/linkedin/callback"})

but I get an undefined method 'request_uri' for #<URI::Generic:0x1b144d20> Exception.

I've tried using the OAuth::Consumer client (where tokens.access_token and tokens.token_secret are the currently valid tokens):

configuration = { site: 'https://api.linkedin.com', authorize_path: '/uas/oauth/authenticate',
                  request_token_path: '/uas/oauth/requestToken', access_token_path: '/uas/oauth/accessToken' }
consumer = OAuth::Consumer.new(ENV['LINKEDIN_APP_ID'], ENV['LINKEDIN_SECRET'], configuration)
access_token = OAuth::AccessToken.new(consumer, tokens.access_token, tokens.token_secret)

but this just gives me back the same access_token and secret.

In the end, I'd love to be able to leverage the existing omniauth-linkedin gem functionality to handle this refresh, any idea if this is possible? Thanks!

Upvotes: 1

Views: 1454

Answers (1)

Kamyar Mohager
Kamyar Mohager

Reputation: 709

In your second approach (using the OAuth::Consumer client and passing in your existing access token and secret) should refresh the token for you. As the documentation states, as long as the current user is logged into LinkedIn.com and the current access token hasn't expired yet, the token will be refreshed.

That doesn't mean necessarily that you'll get a new token. You may get the same one as you had before. The key difference is that the lifespan of the token should 60 days. You can verify this by check the value of oauth_expires_in parameter. It should be set to 5184000.

This blog post goes into detail about refreshing the token: https://developer.linkedin.com/blog/tips-and-tricks-refreshing-access-token

Upvotes: 4

Related Questions