Question

Using linkedin-j, I have the following code in one part of my application

LinkedInOAuthService service = LinkedInOAuthServiceFactory.getInstance()
        .createLinkedInOAuthService(consumerKey, consumerSecret);
LinkedInRequestToken requestToken = 
                    service.getOAuthRequestToken(linkedinCallbackURL);
String authUrl = requestToken.getAuthorizationUrl(); 

I redirect to the page pointed by authUrl and get to the correct LinkedIn page where I authorize my application. Then, the code which generates the page pointed by linkedinCallbackURL will execute this:

String verifier = request.getParameter("oauth_verifier");
LinkedInOAuthService oauthService = 
    LinkedInOAuthServiceFactory.getInstance()
                  .createLinkedInOAuthService(consumerKey, consumerSecret);  

LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken();  
LinkedInAccessToken accessToken = oauthService
            .getOAuthAccessToken(requestToken, verifier);

Unfortunately, I get this error:

com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceException: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/accessToken

Caused by: oauth.signpost.exception.OAuthCommunicationException: Communication with the service provider failed: Server returned HTTP response code: 401 for URL: https://api.linkedin.com/uas/oauth/accessToken

What can be wrong?

Was it helpful?

Solution

It turns out the problem is that I have to use the same LinkedInRequestToken object in both points. To do it, I saved it in the session in the first part:

LinkedInRequestToken requestToken = 
            service.getOAuthRequestToken(linkedinCallbackURL);
session.setAttribute("requestToken", requestToken); // <== THE BEEF
String authUrl = requestToken.getAuthorizationUrl();

Then I retrieved it from session:

LinkedInOAuthService oauthService = LinkedInOAuthServiceFactory.getInstance()
        .createLinkedInOAuthService(consumerKey, consumerSecret);  
// LinkedInRequestToken requestToken = oauthService.getOAuthRequestToken();
LinkedInRequestToken requestToken = 
        (LinkedInRequestToken) session.getAttribute("requestToken")  
LinkedInAccessToken accessToken = oauthService
    .getOAuthAccessToken(requestToken, verifier);

Note: Posting the question and the answer because I searched it A LOT and nobody found this specific problem. Doing it in the spirit of this question on Meta. Also, I did not answer some old questions because this error can happen for a myriad of reasons (it is like NullPointerException for LinkedIn API...) and the questions I have found did not have the same causes as far as I've seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top