Error 401: Unauthorized


#1

Hello All,

I am using sign in with twitter button for oauth/authorizing app. When the user gets redirected to callback url, I sometimes get this error.

<class ‘tweepy.error.TweepError’>: HTTP Error 401: Unauthorized

However, this is not happening all the time. I looked up and this discussion says that this can happen due to incorrect time settings.
http://groups.google.com/group/twitter-development-talk/browse_thread/thread/aadee92bc5c34f29?pli=1

Time on the server is correct. Any suggestion on why this is happening is most welcome.

Thanks,
Yogesh


#2

i get the same. while the login and password are both valid.


#3

For 401 errors, it would be most helpful to include a HTTP request dump of the failing request, or, if that is not possible, a listing of the code you’re using to make the request, in addition to a list of any OAuth libraries you may be using.


#4

HI this is the error I get. I just installed this yesterday

" WP to Twitter successfully contacted your selected URL shortening service. The following link should point to your blog homepage: http://antiagingkundalini.com/?p=
WP to Twitter failed to submit an update to Twitter.
401 Unauthorized: Authentication credentials were missing or incorrect."
I triple check all of the keys and they seemed fine.

Beats me


#5

Just ran into the 401 issue while authenticating

In our case, the 401 error was caused by leaving the ‘callback url’ setting field blank within the app config screens. Try setting something in that field, it isn’t actually used in our case as the callback is specified on each request.


#6

also when i access my account api i got “The remote server returned an error: (401) Unauthorized.” this type of error if any one have solution plz give me blog link…

Thanks


#7

tough i have time corrected in my system still i get the same error…401


#8

I am getting the same error using vb6…


#9

same error


#10

Getting the same error over and over. This is the code im using.
Function Authorization(_Tweet As String, Tweet_url As String) As String

    Dim CS_Key As String = "xxxxxxxxxxxx"  ' Customer Key
    Dim CS_Secret As String = "xxxxxx" ' Consumer Secret
    Dim Token As String = "xxxxxxxx"
    Dim TK_Secret As String = "xxxxxxxxxxxxx"
    Dim oauth_version = "1.0"
    Dim oauth_signature_method = "HMAC-SHA1"
    Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
    Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))


    Dim _Query As String = ""
    _Query = "include_entities=true&oauth_consumer_key=" & CS_Key _
        & "&oauth_nonce=" & oauth_nonce _
        & "&oauth_signature_method=" & oauth_signature_method _
        & "&oauth_timestamp=" & oauth_timestamp _
        & "&oauth_token=" & Token _
        & "&oauth_version=" & oauth_version _
        & "&status=" & Uri.EscapeDataString(_Tweet)

    'Response.Write("Query:" & _Query & "<br>")
    'Response.Flush()

    Dim _Signature As String = "POST&" & Uri.EscapeDataString(Tweet_url) & "&" & Uri.EscapeDataString(_Query)
    'Response.Write("Signature:" & _Signature & "<br>")
    'Response.Flush()

    Dim compositeKey = String.Concat(Uri.EscapeDataString(CS_Secret), "&", Uri.EscapeDataString(TK_Secret))
    'Response.Write("compositeKey:" & compositeKey & "<br>")
    'Response.Flush()

    Dim oauth_signature As String
    Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
        oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(_Signature)))
    End Using

    'Response.Write("oauth_signature:" & oauth_signature & "<br>")
    'Response.Flush()

    Dim _Header As String = ""
    _Header = "OAuth " _
        & "oauth_consumer_key=""" & Uri.EscapeDataString(CS_Key) & """, " _
        & "oauth_nonce=""" & Uri.EscapeDataString(oauth_nonce) & """, " _
        & "oauth_signature=""" & Uri.EscapeDataString(oauth_signature) & """, " _
        & "oauth_signature_method=""" & Uri.EscapeDataString(oauth_signature_method) & """, " _
        & "oauth_timestamp=""" & Uri.EscapeDataString(oauth_timestamp) & """, " _
        & "oauth_token=""" & Uri.EscapeDataString(Token) & """, " _
        & "oauth_version=""" & Uri.EscapeDataString(oauth_version) & """"

    'Response.Write("<hr>" & _Header & "<hr>")
    'Response.Flush()

    Return _Header
End Function

Sub TwitIt(_Tweet As String)


    Dim _Header As String = Authorization(_Tweet, Tweet_url)
    Dim postBody = "status=" + Uri.EscapeDataString(_Tweet) 

    ServicePointManager.Expect100Continue = False
    Dim request As HttpWebRequest = DirectCast(WebRequest.Create(Tweet_url), HttpWebRequest)

    request.Headers.Add("Authorization", _Header)
    request.Method = "POST"
    request.ContentType = "application/x-www-form-urlencoded"
    request.UserAgent = "OAuth gem v0.4.4"
    request.Host = "api.twitter.com"
    request.Accept = "*/*" 

    Using stream As IO.Stream = request.GetRequestStream()
        Dim content As Byte() = ASCIIEncoding.ASCII.GetBytes(postBody)
        stream.Write(content, 0, content.Length)
    End Using
    Dim response As WebResponse = request.GetResponse()
End Sub

Sub Tweet(sender As Object, e As System.EventArgs) 
    TwitIt("Ladies + Gentlemen blah blah")
End Sub

#11

Does anyone still facing this issue?
I do even though I corrected the server time.


#12

I’m facing the same issue atm.
My server time is correct.
My local time is correct.
Everything was working like a charm and suddenly stopped.
Any ideas on it?

[status] => 401 Unauthorized it’s driving me crazy >.<


#13

same error, i’m trying to use it with HybridAuth library.
no body is responsible for this error???
where are api developers?


#14

When creating your application, do not click the “create your access token” until you first click on Settings and change the Application Type to “Read, Write and Access direct messages”.
After your Twitter application has been updated to “Read, Write and Access direct messages”, click on the Home tab, and “create your access token”.
This should do the trick =)


#15

i am trying to login through twitter account, my application throw this error.please help me…
OAuth::Unauthorized
401 Unauthorized


#16

Hello.

I have the same issue, in my case I use Oauth to connect to the rest api without problems, for example I have been able to request the URL"https://api.twitter.com/1/account/rate_limit_status.json" in authenticated mode. When I use it for the twitter sign-in, I receive a “401 Unauthorized”.
This is the url and the Authorization header in the POST request that I used:

URL: https://api.twitter.com/oauth/request_token
Authorization Header: OAuth oauth_consumer_key="", oauth_nonce=“396s34v6s8fvqa8hjlfh6qjqcfcciuqd5h0rbqffnp”, oauth_callback=“http%3A%2F%2FNautorTest.naut”, oauth_signature=“Y3%2FqtjGLdYG3iR7EnzkLMX7qeBU%3D”, oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1345760500”, oauth_version=“1.0”

I verified that the timestamp is correct, and in my Twitter account I have read-write access for my application and the url callback is the same that here is displayed, of course without the encoding.


#17

thanks, that helped a lot!


#18

POST requests are more difficult than GET requests to perform correctly. Did you just omit the consumer key in your example there or are you sending it along with the request? You can also use a GET to oauth/request_token, but you’ll want to master POSTs anyway.

In most cases when a GET succeeds but a POST fails, it has something to do with your signature base string and how it is generated – whether it’s the encoding of parameters correctly or the ordering of parameters or otherwise; usually the problem is there.


#19

Thanks Taylor for your response, the consumer_key in my post is empty but in my java code is well defined, ¿were I found the docs where is well defined how to generate the signature? In previous post I say that rest api calls is working fine, I understand that the way of make the signature is not the problem because rest api calls is ok.

One more question, is the request_token call signed in the same way as the rest api calls is?

Thanks again!

Best regards!


#20

Hello again, I am unable to generate oauth_signature correctly.

My explanation: I do a main class with only POST oath/request_token functionality for reproduce de same oath_signature in this example https://dev.twitter.com/docs/auth/implementing-sign-twitter.

Following the steps in https://dev.twitter.com/docs/auth/creating-signature I do this methods in java to generate oath_signature parameter:

--------------START JAVA CODE----------------

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SignatureException;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

public class TestLauncher {

public static void main(String[] args) {
	String response=TestLauncher.executeURL("https://api.twitter.com/oauth/request_token", "http://localhost/sign-in-with-twitter/");
	System.out.println("response="+response);
}

public static String executeURL(String url,String oauth_callback){
	if(url==null||url.isEmpty()||oauth_callback==null||oauth_callback.isEmpty()) return null;
	String page="";
    try{    
		HttpHost targetHost = new HttpHost("api.twitter.com", 443, "https");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Create request
                // You can also use the full URI http://www.google.com/
                HttpPost httppost = TestLauncher.OAuthConnection(url,oauth_callback);
                // Execute request
                HttpResponse response = httpclient.execute(targetHost, httppost);

                HttpEntity entity = response.getEntity();
                Header header=entity.getContentType();
                HeaderElement[] he=header.getElements();
                for(int i=0;i<he.length;i++) page+=" ["+he[i].getName()+"<"+he[i].getParameterCount()+">"+he[i].getValue()+"]";
                String line="";BufferedReader in=null;
    			try{in=new BufferedReader(new InputStreamReader(entity.getContent()));}catch(Exception ex){
    				try{Thread.sleep(10000);in=new BufferedReader(new InputStreamReader(entity.getContent()));}catch(Exception ex2){}
    			}
    			while(in!=null&&((line=in.readLine())!=null)){
    			   page+=line + "\\n";
    			}
            } finally {
                httpclient.getConnectionManager().shutdown();
            }
}catch(Exception e){e.printStackTrace();}
	return page;
}

private static HttpPost OAuthConnection(String url,String url_callback) throws IOException{
	 HttpPost httppost = new HttpPost(url);
	 	String oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w";
		String oauth_nonce="ea9ec8429b68d6b77cd5600adbbb0456";
		String oauth_callback=url_callback;
		String oauth_signature_method="HMAC-SHA1";
		String oauth_timestamp="1318467427";
		String oauth_version="1.0";
		
		SortedMap<String,String> map=new TreeMap<String,String>();
		map.put("oauth_consumer_key",URLEncoder.encode(oauth_consumer_key,"UTF-8"));
		map.put("oauth_callback",URLEncoder.encode(oauth_callback,"UTF-8"));
		map.put("oauth_nonce",URLEncoder.encode(oauth_nonce,"UTF-8"));
		map.put("oauth_signature_method",URLEncoder.encode(oauth_signature_method,"UTF-8"));
		map.put("oauth_timestamp",URLEncoder.encode(oauth_timestamp,"UTF-8"));
		map.put("oauth_version",URLEncoder.encode(oauth_version,"UTF-8"));
		URL url_object = new URL(url);
		if(url_object.getQuery()!=null&&!url_object.getQuery().isEmpty()){
			String[] params=url_object.getQuery().split("&");
			for(int i=0;i<params.length;i++) map.put(URLEncoder.encode(params[i].split("=")[0],"UTF-8"),URLEncoder.encode(params[i].split("=")[1],"UTF-8"));
		}
		String url_base=URLEncoder.encode(url_object.getProtocol()+"://"+url_object.getHost()+url_object.getPath(),"UTF-8");
		String oauth_signature=TestLauncher.generateSignature(map,"POST",url_base);

		String auth_values="OAuth oauth_callback=\""+URLEncoder.encode(oauth_callback,"UTF-8")+"\", ";
		auth_values+="oauth_consumer_key=\""+URLEncoder.encode(oauth_consumer_key,"UTF-8")+"\", ";
		auth_values+="oauth_nonce=\""+URLEncoder.encode(oauth_nonce,"UTF-8")+"\", ";
		auth_values+="oauth_signature=\""+URLEncoder.encode(oauth_signature,"UTF-8")+"\", ";
		auth_values+="oauth_signature_method=\""+URLEncoder.encode(oauth_signature_method,"UTF-8")+"\", ";
		auth_values+="oauth_timestamp=\""+URLEncoder.encode(oauth_timestamp,"UTF-8")+"\", ";
		auth_values+="oauth_version=\""+URLEncoder.encode(oauth_version,"UTF-8")+"\"";
		httppost.setHeader("Authorization",auth_values);
		System.out.println("auth_values="+auth_values);
	return httppost;
}

private static String generateSignature(SortedMap<String,String> map,String httpMethod,String url_base) throws UnsupportedEncodingException{
	String params="";
	Iterator<String> keys=map.keySet().iterator();
	Iterator<String> values=map.values().iterator();
	while(keys.hasNext()){
		params+=keys.next()+"="+values.next();
		if(keys.hasNext()) params+="&";
	}
	String data=httpMethod+"&"+url_base+"&"+URLEncoder.encode(params, "UTF-8");
	System.out.println("generateSignature() data="+data);
	String consumer_secret="XXXXX";
	String key=URLEncoder.encode(consumer_secret, "UTF-8");
	String output=null;
	try {
		output=TestLauncher.calculateHMAC_SHA1(data, key);
	} catch (SignatureException e) {
		System.out.println("ERROR HMAC-SHA1: KEY["+key+"] - DATA["+data+"]");
		e.printStackTrace();
	}
	return output;
}

private static String calculateHMAC_SHA1(String data, String key) throws java.security.SignatureException{
	String result=null;
	try{
		SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		mac.init(signingKey);
		byte[] rawHmac = mac.doFinal(data.getBytes());
		result = new String(Base64.encodeBase64(rawHmac)).trim();
	}catch(Exception e){
		throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
	}
	return result;
}

}

----------------END JAVA CODE-----------------

Executing this code I see that the generated oath_signature parameter is oauth_signature=“JhNSoG1nhY6%2F0IIpP22lRaOng40%3D” and in twitter’s example is oauth_signature=“F1Li3tvehgcraF8DMJ7OyxO4w9Y%3D”. This is my problem, I am wrong or I have an error generating the oauth_signature parameter.

Please can anybody help me?

Thanks and Best Regards!!