Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twitter request_token endpoint always returns "couldn't authenticate you"

I am writing a simple twitter login and trying to get request Token in order to redirect user to access token but i always end up with couldn't authenticate you error i tried to add signature as last header it did not work too. when i remove some header i get bad authentication data error so with this configuration i assume everything is proper i just can not figure what i am doing wrong and twitter refuses to send the request token back.

here is my code

'use strict';
const https = require("https");
const cfg = require('./config');
// const cfg=require(`${__dirname}/config`);
const qs = require("querystring");
const esc = qs.escape;
const crypto = require('crypto');
const HMAC = crypto.createHmac;
class twitter {
    constructor(o) {
        // if (!o || !o.consumer_key || !o.consumer_secret) throw new Error("Missing Paramaters");
        this.id = o.consumer_key;
        this.secret = o.consumer_secret;
    }
    getNonce() {
        let num = 32;
        let preDefined = Date.now().toString().split("");
        num -= preDefined.length;
        while (num--) {
            preDefined.push(Math.round(Math.random() * 31).toString(32));
        }
        return (new Buffer(preDefined.join("")).toString("base64"));
    }
    getSignature(HTTPmethod, url, parameters, tokenSecret) {
        const method = HTTPmethod.toUpperCase();
        const baseUrl = url;
        const params = parameters;
        const sorted = Object.keys(params).sort();
        let baseString = `${esc(method)}&${esc(baseUrl)}`;
        let signingKey = `${esc(this.secret)}&`
        signingKey += tokenSecret ? esc(tokenSecret) : "";
        let firstRun = true;
        sorted.forEach(param => {
            if (firstRun) {
                baseString += "&";
                firstRun = false;
            }
            else {
                baseString += esc("&");
            }
            baseString += esc(`${param}=${params[param]}`);
        });
        return HMAC('SHA1', signingKey).update(baseString).digest('base64');
        // return baseString;
    }
    getHeaders(httpMethod, baseUrl, additional, token, tokenSecret, extraHeaders) {
        let headers = {
            oauth_consumer_key: this.id,
            oauth_nonce: this.getNonce(),
            oauth_signature_method: "HMAC-SHA1",
            oauth_timestamp: Math.floor(Date.now() / 1000),
            oauth_version: "1.0"
        }
        if (extraHeaders) {
            for (let i in extraHeaders) {
                headers[i] = extraHeaders[i];
            }
        }
        if (token) headers.oauth_token = token;
        let params = headers;
        if (additional) {
            for (let i in additional) {
                params[i] = additional[i];
            }
        }
        // const signature = this.getSignature(httpMethod, baseUrl, params, tokenSecret || "");
        headers.oauth_signature = this.getSignature(httpMethod, baseUrl, params, tokenSecret || "");
        let header = `OAuth `;
        let firstRun = true;
        const sorted = Object.keys(headers).sort();
        sorted.forEach(i => {
            let prefix;
            if (firstRun) {
                prefix = "";
                firstRun = false;
            }
            else {
                prefix = ", ";
            }
            header += `${prefix}${esc(i)}="${esc(headers[i])}"`
        });
        // header += `, oauth_signature="${esc(signature)}"`;
        return header;
    }
    getRequestToken(cb) {
        if (!cb) throw new Error('callback must be defined');
        const callbackUrl = cb;
        let headers = this.getHeaders("POST", "https://api.twitter.com/oauth/request_token", false, false, false, {
            oauth_callback: callbackUrl
        });
        const reqParams = {
            method: "POST",
            host: "api.twitter.com",
            path: "/oauth/request_token",
            headers: { "Authorization": headers }
        }
        const req = https.request(reqParams, res => {
            let data = "";
            res.on("data", d => data += d);
            res.on("end", _ => console.log(data));
        }); req.end();
        console.log(req._headers);
    }
}
(new twitter({
    consumer_key: cfg.id,
    consumer_secret: cfg.secret
})).getRequestToken("https://127.0.0.1/twitter");
like image 866
nikoss Avatar asked Apr 15 '16 22:04

nikoss


Video Answer


1 Answers

the key was double escaping the basestring parameters

like image 172
nikoss Avatar answered Oct 07 '22 23:10

nikoss