401 Unauthorized error while trying to get an access_token


#1

Hey, All.

I keep getting the 401 Unauthorized when trying to get an access token. My env is: rails 2.3, oauth 0.4.5, twitter 0.9.12, VmWare CentOS 5.4 instance.

callback_url is set to http://127.0.0.1/auth/twitter/callback

It works when I post to get a request token.

@oauth = Twitter::OAuth.new(consumer_key, consumer_secret)
@oauth.set_callback_url(“http://127.0.0.1:3000/auth/twitter/callback”)
session[‘rtoken’] = @oauth.request_token.token
session[‘rsecret’] = @oauth.request_token.secret
redirect_to @oauth.request_token.authorize_url

The post headers are:

<- “POST /oauth/request_token HTTP/1.1\r\nAccept: /\r\nConnection: close\r\nUser-Agent: OAuth gem v0.4.5\r\nAuthorization: OAuth oauth_body_hash=“2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D”, oauth_callback=“http%3A%
2F%2F127.0.0.1:3000%2Fauth%2Ftwitter%2Fcallback”, oauth_consumer_key=“Y7zOGGmY2bIGmjDshodCB”, oauth_nonce=“RX8NCSml55l670erFLMTB0ueJe9v5pH3XJ4J2e06ws”, oauth_signature=“4KS%2BSv%2FkE8M
ZC9rWy56UCHIOAM0%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1324408450”, oauth_version=“1.0”\r\nContent-Length: 0\r\nHost: api.twitter.com\r\n\r\n”
-> “HTTP/1.1 200 OK\r\n”
-> “Date: Tue, 20 Dec 2011 19:14:13 GMT\r\n”
-> “Status: 200 OK\r\n”
-> “X-Transaction: f18a2fd632961b47\r\n”
-> “ETag: “0705fcbbad49073290d2a133e0fe0ca0”\r\n”
-> “X-Frame-Options: SAMEORIGIN\r\n”
-> “Last-Modified: Tue, 20 Dec 2011 19:14:13 GMT\r\n”
-> “X-Action-Name: request_token\r\n”
-> “X-Runtime: 0.01440\r\n”
-> “Content-Type: text/html; charset=utf-8\r\n”
-> “Content-Length: 144\r\n”
-> “Pragma: no-cache\r\n”
-> “X-Controller-Class: OauthController\r\n”
-> “X-Revision: DEV\r\n”
-> “Expires: Tue, 31 Mar 1981 05:00:00 GMT\r\n”
-> “Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\n”
-> “X-MID: 05c161199aa367c46a8bff0ecaecce7ab42182d7\r\n”
-> “Set-Cookie: k=10.40.1.105.1324408453363953; path=/; expires=Tue, 27-Dec-11 19:14:13 GMT; domain=.twitter.com\r\n”
-> “Set-Cookie: guest_id=v1%3A132440845337324474; domain=.twitter.com; path=/; expires=Fri, 20-Dec-2013 07:14:13 GMT\r\n”
-> “Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCP445Vw0AToHaWQiJWZiNmE3ZTI0ZmM4OWMw%250AOWUxOGE2ODBlY2Y1OGUxNmUxIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA–b8ebdcc81c
75f000067a2b92864d6bdf9939cebe; domain=.twitter.com; path=/; HttpOnly\r\n”
-> “Vary: Accept-Encoding\r\n”
-> “Server: tfe\r\n”
-> "\r\n"
reading 144 bytes…
-> "oauth_token=Xmk2t4BuKPGLrDqXvmtOPEgCH1f1fm91l434xPDM&oauth_token_secret=Nt2vyf7Fpttin3tMoTQGreNqBlBzeXMoFAHhgfu0P0&oauth_callback_confirmed=true"
read 144 bytes

After authenticated the access to the app, twitter redirect the browser to my app. However, it failed now.

@oauth = Twitter::OAuth.new(consumer_key, consumer_secret)
@oauth.authorize_from_request(session[‘rtoken’], session[‘rsecret’], params[:oauth_verifier])

OAuth::Unauthorized (401 Unauthorized):
oauth (0.4.5) lib/oauth/consumer.rb:219:in token_request' oauth (0.4.5) lib/oauth/tokens/request_token.rb:18:inget_access_token’

The post headers are:

<- “POST /oauth/access_token HTTP/1.1\r\nAccept: /\r\nConnection: close\r\nUser-Agent: OAuth gem v0.4.5\r\nAuthorization: OAuth oauth_body_hash=“2jmj7l5rSw0yVb%2FvlWAYkK%2FYBwk%3D”, oauth_consumer_key=“Y7zOGGmY2bIGmjDshodCB”, oauth_nonce=“UTUq2WeWgdNFL2I6r82cZWw7NNg8NK7QF56lBYNEuk”, oauth_signature=“xQl6FZ7voNMzgf3eulW1%2BV11IO0%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1324408456”, oauth_verifier=“ahmlGETQUKtGV5a31kpudctdOxBeieraPUTMoFzA”, oauth_version=“1.0”\r\nContent-Length: 0\r\nHost: api.twitter.com\r\n\r\n”
-> “HTTP/1.1 401 Unauthorized\r\n”
-> “Date: Tue, 20 Dec 2011 19:14:18 GMT\r\n”
-> “Status: 401 Unauthorized\r\n”
-> “X-Transaction: 87eb7894d23e0456\r\n”
-> “X-Frame-Options: SAMEORIGIN\r\n”
-> “Last-Modified: Tue, 20 Dec 2011 19:14:18 GMT\r\n”
-> “X-Action-Name: access_token\r\n”
-> “X-Runtime: 0.01011\r\n”
-> “Content-Type: text/html; charset=utf-8\r\n”
-> “Content-Length: 1\r\n”
-> “Pragma: no-cache\r\n”
-> “X-Controller-Class: OauthController\r\n”
-> “X-Revision: DEV\r\n”
-> “Expires: Tue, 31 Mar 1981 05:00:00 GMT\r\n”
-> “Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0\r\n”
-> “X-MID: d595eb659f025f11d91b432ec6f44e12940cad41\r\n”
-> “Set-Cookie: k=10.35.30.123.1324408458105733; path=/; expires=Tue, 27-Dec-11 19:14:18 GMT; domain=.twitter.com\r\n”
-> “Set-Cookie: guest_id=v1%3A132440845811239885; domain=.twitter.com; path=/; expires=Fri, 20-Dec-2013 07:14:18 GMT\r\n”
-> “Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCIFL5Vw0AToHaWQiJWY1YjQwNWZjNzQ2YWM2%250AOWVhOWMzODgzODMyNWIzODBmIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA–778f1de49d198703caf9c62dc805c51f19ccff7e; domain=.twitter.com; path=/; HttpOnly\r\n”
-> “Vary: Accept-Encoding\r\n”
-> “Server: tfe\r\n”
-> "\r\n"
reading 1 bytes…
-> " "

BTW, if I don’t set the callback url, after authenticated to the app, twitter will directly show me a pin code and I can use the pin code to authenticate successfully.

How could be the problem? Thanks very much!


#2

Few things:

If it’s possible to do so, disable oauth_body_hash support in the Ruby gem. This is not a standard part of the OAuth specification and in fact violates the specification by making the parameter begin with “oauth_” – Twitter does not support this non-spec feature. It may cause unwanted results.

The request to oauth/access_token you’re showing here appears to be missing an oauth_token (and likely wasn’t signed with the oauth_token_secret being part of the composite signing secret). I imagine it likely has something to do with how you’re storing the values from request token in the session and then obtaining them for the access token step.


#3

Thanks very much! It does because missing the parameter oauth_token while trying to get an access token.

However, it’s weird that oauth_token is not included in the header because I’m using the OAuth gem which should work. So I try to debug and see what’s wrong. Strangely, it just works. oauth_token is in the header. And I changed nothing.


#4

Update:

It doesn’t always work when you use http instead of https to request the request_token and access_token. Always means sometimes It works. Maybe that’s because I’m using local to test the app.

However, after making the changes to the gem to force using SSL, then it works. At least haven’t got the errors till now.


#5

hi
happy new year to all,

org.scribe.model.Token accessToken = twitterProvider.getOAuthService().getAccessToken(requestToken, new Verifier(verifier));
System.out.println(“accessToken”+accessToken);

   if (accessToken == null) {
	           return "connect/twitterConnect";
	    }
 
   if (accessToken != null) {

"in this location how to get login user data "

please help me

Thank’you

k.praveen
}


#6

Use the access token you’ve retrieved to make a signed API request to users/show or account/verify_credentials.


#7

public OAuthService getOAuthService() {
OAuthConfig config = new OAuthConfig();
config.setRequestTokenEndpoint(“https://api.twitter.com/oauth/request_token”);
config.setAccessTokenEndpoint(“https://api.twitter.com/oauth/access_token”);
config.setAccessTokenVerb(Verb.POST);
config.setRequestTokenVerb(Verb.POST);
config.setApiKey(apiKey);
config.setApiSecret(apiSecret);
config.setCallback(callbackUrl);

    return new OAuth10aServiceImpl(
            new HMACSha1SignatureService(),
            new TimestampServiceImpl(),
            new BaseStringExtractorImpl(),
            new HeaderExtractorImpl(),
            new TokenExtractorImpl(),
            new TokenExtractorImpl(),
            config);
}

@RequestMapping("/twitter")
public String getsocialurl(WebRequest request,HttpServletRequest req) {
Token requestToken = twitterProvider.getOAuthService().getRequestToken();
request.setAttribute(“twitter_request_token”, requestToken, WebRequest.SCOPE_SESSION);
return “redirect:” + twitterProvider.getAuthorizeUrl() + “?oauth_token=” + (requestToken).getToken();
}
//after userlogin redirect to this controller

@RequestMapping(value = "/userdata", method = RequestMethod.GET, params = "oauth_token")
public String authorizeTwitterCallback(@RequestParam(value = "oauth_verifier", defaultValue = "verifier") String verifier,
                                WebRequest request,HttpServletRequest req) {
Token requestToken = (Token)request.getAttribute("twitter_request_token", WebRequest.SCOPE_SESSION);

this requestToken is null

Token accessToken = (Token) twitterProvider.getOAuthService().getAccessToken(requestToken, new Verifier(verifier));
Cant extract a token from null object or an empty string
}
i got those errors please tell me what is the problem.
give me exact code line of this

please help me
praveen


#8

@yedingding
In your post to get the accesstoken your content-lenght couldn’t been 0 except you’re missing to include oauth_verifier in the Post-body.
Verify that your request has this parameter.


#9

Hi,
Im using oauth ruby gem -v 0.4.7 with rails 2.3.11. The signup with twitter was working for
nearly 2 years. Currenly i checked my system is not working yet. My app with twitter is working
but the callback url gives an error like “Exception in exchange_request_for_access_token: 401 Unauthorized”. I’ve changed the call backurl too and checked again but no luck. Can anyone help me out?.