Encountering an issue with sending a direct message on Twitter through OAuth

I am currently developing a JavaScript script to work alongside my C++ application for sending direct messages to users. The script is responsible for constructing the request that I send out. However, whenever I make a request, I keep getting errors like "Incorrect signature" or "can not authenticate you." Can anyone spot any mistakes or missing elements in what I'm doing? I am actively investigating this issue. Thank you in advance.

Here is a snippet of the JavaScript code:

var nDate = new Date();
var epoch = nDate.getTime();
var nonce = "";

nonce = Base64.encode(epoch + randomString()); 

var Parameters = [
   "oauth_consumerkey=" + sConsumerKey,
   "oauth_nonce=" + nonce,
   "oauth_signature_method=HMAC-SHA1",
   "oauth_timestamp=" + epoch,
   "oauth_token=" + sAccessToken,
   "oauth_version=1.0",
   "text=" + sText,
   "user=" + sUser
];

var SortedParameters = Parameters.sort(); 
var joinParameters = SortedParameters.join("&");
var encodeParameters = escape(joinParameters);

signature_base_string = escape("POST&" + NormalizedURL + "&" + encodeParameters);

signature_key = sConsumerSecret + "&" + sAccessSecret;

signature = Base64.encode(hmacsha1(signature_base_string, signature_key));

sAuthHeader = "
  OAuth realm=, 
  oauth_nonce=" + nonce + ",
  oauth_timestamp=" + epoch + ",     
  oauth_consumer_key=" + sConsumerKey + ",
  oauth_signature_method=HMAC-SHA1, 
  oauth_version=1.0,
  oauth_signature=" + signature + ",
  oauth_token=" + sAccessToken + ",
  text=" + sText;

goNVOut.Set("Header.Authorization: ", sAuthHeader);

Answer №1

Ensure to take note of the following important points:

  • The "escape" function in JavaScript is not suitable for OAuth URL encoding, as outlined in the OAuth Spec.

5.1. Parameter Encoding

All parameter names and values are escaped using the [RFC3986] percent-encoding (%xx) mechanism. Characters not in the unreserved character set ([RFC3986] section 2.3) MUST be encoded. Characters in the unreserved character set MUST NOT be encoded. Hexadecimal characters in encodings MUST be upper case. Text names and values MUST be encoded as UTF-8 octets before percent-encoding them per [RFC3629].

        unreserved = ALPHA, DIGIT, '-', '.', '_', '~'

Beware that the escape function in JavaScript may allow certain symbols like @ * + / to pass through without being properly escaped. This can lead to discrepancies during signature signing, affecting the outcome compared to server-side computations.

  • Remember to perform URL encoding on your base URI, NormalizedURL, as well.

Accurate encoding is often the most challenging aspect of implementing OAuth. Ensure that your "url_encode" function uses uppercase letters consistently.

Below is a snippet of my C++ code for performing URL encoding. It could be optimized further but should be straightforward to comprehend.

char hexdigit(int ch)
{
    assert(ch < 16);
    assert(ch >= 0);
    if (ch >= 10)
        return 'A' + ch - 10;
    return '0' + ch;
}

std::string url_encode(const std::string &to_encode)
{
    std::stringstream ss;
    for (std::string::const_iterator ich = to_encode.begin();
         ich != to_encode.end();
         ++ich)
    {
        unsigned char ch = (unsigned char)*ich;
        if (isalpha(ch) || isdigit(ch) || ch == '-' || ch == '_' || ch == '.' || ch == '~')
        {
            ss << ch;
        }
        else
        {
            ss << '%';
            ss << hexdigit(ch >> 4);
            ss << hexdigit(ch & 0xf);
        }
    }

    std::string encoded = ss.str();
    return encoded;
}

Wishing you all the best!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize JSON parsing to extract and store data into an object

I'm currently working on extracting specific objects from a parsed JSON stored within an object named data.json. var data = { json: '', text: '', welcome: '', q1: '', } let foo = await fetch(spr ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Steps for serving a "noop" document via HTTP

I am in the process of creating a CGI script that performs various functions. I am striving to maintain simplicity and portability within the script. My main objective is to provide users with a way to send a message to the server without losing the curren ...

Understanding Three.js Fundamentals: Resolving GLTFLoader Animation and Variable Not Found Issues

My understanding of JS is very basic. After exploring the three.js docs on Loading 3D models, I managed to successfully render a 3D object and center it: const loader = new GLTFLoader(); loader.load( 'Duck.gltf', function ( duck ) { con ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

Tips for transferring variables between two browser windows within the same session of Internet Explorer 11

Is there a way to prevent a parameter from displaying in the address bar and avoid storing it locally? For example, the parameter value is like vndfj/dfgdgdfg12/dg==. I attempted the following code, but it does not work on IE and Edge browsers: let data ...

Express application failed to deploy due to boot timeout error R10

After researching extensively on Stack Overflow and various other websites, I have been unable to solve a problem with my small Express app using ES6 syntax. Upon deploying it to Heroku, I encountered the following error: LOGS : 2021-04-09T12:14:14.688546 ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Display loading icon in AngularJS during template retrieval

Imagine I have this specific directive: angular .module('app.widgets') .directive('myCalendarRange', myCalendarRange); function myCalendarRange () { var directive = { link: link, templateUrl: '/template/is/located ...

React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded? I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set withou ...

It is not possible to submit a form within a Modal using React Semantic UI

I am working on creating a modal for submitting a form using React semantic UI. However, I am encountering an issue with the submit button not functioning correctly and the answers not being submitted to Google Form even though I have included action={GO ...

How to trigger a function when clicking on a TableRow in React using MaterialUI

Can someone help me understand how to add an onClick listener to my TableRow in React? I noticed that simply giving an onClick prop like this seemed to work: <TableRow onClick = {()=> console.log("clicked")}> <TableCell> Content </Ta ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

issue with displaying video as background in angularjs

Trying to create a video background using Ionic and AngularJS. I attempted to insert this code into the HTML, but the video is not working: <source class="cvideo" src="background/{{current.currently.icon}}" type="video/webm"> When running it, the r ...

After the initial iteration, the .length function ceases to function properly when

A validation method is set up to check the length of a user input field. It functions properly on the initial try, but does not update if I go back and modify the field. $("#user").blur(function () { if ($("#user").val().length < 3) { $("#userval ...

Utilizing a variable name to specify an array or object for searching in Javascript and jQuery

Looking to improve my JavaScript skills as a beginner. I have a program that can randomly select an item from an object, but now I want it to pick another item from an object with the same name as the first selection. However, I'm struggling with usin ...

Creating a stunning art exhibition using React Native

Currently, I am in the process of creating a gallery component that utilizes both the scrollview and image APIs. I'm curious about how the scrollview manages its child components when it scrolls down. Does it unmount the parts that are not currently ...

Locate and retrieve the final character of the class identifier

I need to extract a specific class attribute value from a dynamically generated HTML element using JavaScript. The class name follows a pattern like sf-single-children-*, where the asterisk (*) represents a variable number based on the number of child elem ...

Verify that the length of all input fields is exactly 7 characters

My task involves checking the length of multiple input fields that share a common class. The goal is to verify that all fields have a length of 7. After attempting a solution, I encountered an issue where even if the length of all fields is indeed 7, the ...

Trouble with Loading Bootstrap CSS File

Having some trouble with Bootstrap - I'm following a basic tutorial and everything seems to be working fine, except the CSS file isn't loading properly. I've checked on StackOverflow but couldn't find a solution that worked for me. Both ...