Error 401: Unauthorized


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.

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



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


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.


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:
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


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.


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…



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


I am getting the same error using vb6…


same error


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>")

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

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

    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>")

    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>")

    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 = ""
    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


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


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 >.<


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


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 =)


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



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"" 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:

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.


thanks, that helped a lot!


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.


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!


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

Following the steps in I do this methods in java to generate oath_signature parameter:

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

package test;

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("", "http://localhost/sign-in-with-twitter/");

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

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {
                // Create request
                // You can also use the full URI
                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){}
    			   page+=line + "\\n";
            } finally {
}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>();
		URL url_object = new URL(url);
			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")+"\", ";
	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();
		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+"]");
	return output;

private static String calculateHMAC_SHA1(String data, String key) throws{
	String result=null;
		SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA1");
		Mac mac = Mac.getInstance("HmacSHA1");
		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!!