Cannot authenticate authentication error using twitter api? - javascript

I am using twitter api using Auth 1.0 and it is working well when using url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'
but when I am using https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular api its returning
{
"errors": [
{
"code": 32,
"message": "Could not authenticate you."
}
]
}
Now I am not understanding why it is happening...
Following is the header I am making:
function buildRequestHeader(httpMethod, URL) {
parameters = {
oauth_consumer_key: CONSUMER_KEY,
oauth_token: ACCESS_TOKEN,
oauth_nonce: getNonce(),
oauth_timestamp: getTimestamp(),
oauth_signature_method: 'HMAC-SHA1',
oauth_version: '1.0',
},
signature = oauthSignature.generate(httpMethod, URL, parameters, CONSUMER_SECRET, ACCESS_TOKEN_SECRET,{ encodeSignature: false }),
authString = 'OAuth oauth_consumer_key=' + parameters.oauth_consumer_key + ',oauth_token=' + parameters.oauth_token + ',oauth_signature_method=HMAC-SHA1,oauth_timestamp=' + parameters.oauth_timestamp + ',oauth_nonce=' + parameters.oauth_nonce + ',oauth_version=1.0,oauth_signature=' + encodeURIComponent(signature);
return authString;
console.log('>>>>>>>', authString);
}
It is returning me header for twitter which is working well for url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' but error code 32 for https://api.twitter.com/1.1/search/tweets.json?q=nasa&result_type=popular api.Thank you .Any help will be appr

It's been a while, but I believe that your oath parameters need to appear in the AuthString in alphabetical order by parameter name.

Please check your Twitter Application. Twitter Application. In App details, 'Sign in with Twitter' must be 'enabled'.

Related

MemberOf in Graph Me api azure AD

I am trying to get the member groups of the user to whom user belongs using azure graph api but it is not returning memberof in the api. I am using auth0 for the authentication.
Here is the java script code which I am using.
function(accessToken, ctx, cb) {
const jwt = require('jsonwebtoken#7.1.9');
console.log('azure - retrieve user profile');
// Retrieve the profile from Azure
request.get(
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf', {
headers: {
'Authorization': 'Bearer ' + accessToken,
},
json: true
},
function(e, r, profile) {
if (e) {
console.log('azure - error while retrieving user profile:');
console.log(e);
return cb(e)
}
if (r.statusCode !== 200) {
console.log('azure - error while retrieving user profile: ' + r.statusCode);
return cb(new Error('StatusCode: ' + r.statusCode));
}
console.log('azure - retrieved user profile.');
// Get the tenant id from the access token
let decodedToken = jwt.decode(accessToken);
let auth0Profile = {
user_id: profile.id,
given_name: profile.givenName,
family_name: profile.surname,
email: profile.mail || profile.otherMails[0] || profile.userPrincipalName,
email_verified: true,
name: profile.givenName + ' ' + profile.surname,
tenant_id: decodedToken.tid,
identification_value: decodedToken.tid,
user_principal_name: profile.userPrincipalName,
user_department: profile.department,
user_member: profile.memberOf
};
cb(null, auth0Profile);
}
);
}
I have added scope (User.Read Directory.Read.All) in Auth0 for the api call.
Can some one let me know why I am not getting memberOf?
If you want to get member groups of the user, along with multiple attributes, the query will not return the expected results.
I tried checking the same query in Microsoft Graph Explorer.
'https://graph.microsoft.com/v1.0/me?$select=id,mail,givenName,surname,userPrincipalName,otherMails,department,memberOf'
Even
for that, except memberOf, all objects displayed:
For getting memberOf, you have to query separately like below:
https://graph.microsoft.com/v1.0/me/memberOf
So, for the workaround, you can make use of the above query by giving it separately without querying with other attributes.
Also please make sure to add GroupMember.Read.All permissions in the scope as mentioned in this Microsoft Doc.
Please find below links if they are helpful: Ref1, Ref2

How can I send email notifications with Parse and Mandrill?

I am trying to use Mandrill to send an event-based email notification to the users of my web app. I am using Parse with Back4App.
In this tutorial (https://docs.back4app.com/docs/integrations/parse-server-mandrill/), the hosting providers suggest using the following method to call the Mandrill cloud code from an Android application:
public class Mandrill extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("your back4app app id”)
.clientKey(“your back4app client key ")
.server("https://parseapi.back4app.com/").build()
);
Map < String, String > params = new HashMap < > ();
params.put("text", "Sample mail body");
params.put("subject", "Test Parse Push");
params.put("fromEmail", "someone#example.com");
params.put("fromName", "Source User");
params.put("toEmail", "other#example.com");
params.put("toName", "Target user");
params.put("replyTo", "reply-to#example.com");
ParseCloud.callFunctionInBackground("sendMail", params, new FunctionCallback < Object > () {
#Override
public void done(Object response, ParseException exc) {
Log.e("cloud code example", "response: " + response);
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mandrill);
}
}
How can I implement this in JavaScript with the Parse JavaScript SDK?
This is what I've done so far but it won't send an email. I have Mandrill set up, as well as a verified email domain and valid DKIM and SPF.
// Run email Cloud code
Parse.Cloud.run("sendMail", {
text: "Email Test",
subject: "Email Test",
fromEmail: "no-reply#test.ca",
fromName: "TEST",
toEmail: "test#gmail.com",
toName: "test",
replyTo: "no-reply#test.ca"
}).then(function(result) {
// make sure to set the email sent flag on the object
console.log("result :" + JSON.stringify(result));
}, function(error) {
// error
});
I don't even get a result in the console, so I figure the cloud code is not even executing.
You have to add the Mandrill Email Adapter to the initialisation of your Parse Server, as described on their Github page. Also check the Parse Server Guide for how to initialise or use their example project.
Then set up Cloud Code by following the guide. You'll want to either call a Cloud Code function using your Android app or from any Javascript app, or use beforeSave or afterSave hooks of a Parse Object directly in Cloud Code, which allow you to send Welcome Emails when a user signs up. That could come in handy if you want to implement behaviour based emails based on object updates. Plus, because it is on the server and not the client, it is easier to maintain and scale.
To make the Cloud Code function actually send an email via Mandrill, you need to add some more code to your Cloud Code function. First, add a file with these contents:
var _apiUrl = 'mandrillapp.com/api/1.0';
var _apiKey = process.env.MANDRILL_API_KEY || '';
exports.initialize = function(apiKey) {
_apiKey = apiKey;
};
exports.sendTemplate = function(request, response) {
request.key = _apiKey;
return Parse.Cloud.httpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
url: 'https://' + _apiUrl + '/messages/send-template.json',
body: request,
success: function(httpResponse) {
if (response) {
response.success(httpResponse);
}
return Parse.Promise.resolve(httpResponse);
},
error: function(httpResponse) {
if (response) {
response.error(httpResponse);
}
return Parse.Promise.reject(httpResponse);
}
});
};
Require that file in your Cloud Code file, and use it like any other Promise.
var Mandrill = require("./file");
Mandrill.sendTemplate({
template_name: "TEMPLATE_NAME",
template_content: [{}],
key: process.env.MANDRILL_API_KEY,
message: {
global_merge_vars: [{
name: "REPLACABLE_CONTENT_NAME",
content: "YOUR_CONTENT",
}],
subject: "SUBJECT",
from_email: "YOUR#EMAIL.COM",
from_name: "YOUR NAME",
to: [{
email: "RECIPIENT#EMAIL.COM",
name: "RECIPIENT NAME"
}],
important: true
},
async: false
})
.then(
function success() {
})
.catch(
function error(error) {
});
Make sure you create a template on Mailchimp, right click it and choose "Send to Mandrill", so that you can use that template's name when sending via the API.
It's a bit involved, but once set up, it works like a charm. Good luck!

Twitter REST API: Bad Authentication data

I'm trying to post a tweet but for any reason it doesn't work as expected.
I suspect that the issue could be related to the signature string, but following what twitter says according to signing requests looks ok.
Here is my code:
function postTweet(user_id, AccessToken, AccessTokenSecret) {
var base_url = 'https://api.twitter.com/1.1/statuses/update.json',
oauth_nonce = randomString(),
oauth_signature,
oauth_timestamp = Math.floor(new Date().getTime() / 1000),
reqArray,
req,
signature_base_string,
signing_key;
reqArray = [
"include_entities=true",
'oauth_consumer_key="' + CONFIG.TWITTER_CONSUMER_KEY + '"',
'oauth_nonce="' + oauth_nonce + '"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="' + oauth_timestamp + '"',
'oauth_token="' + AccessToken + '"',
'oauth_version="1.0"',
'status=' + encodeURIComponent("hello world")
];
req = reqArray.sort().join('&');
signature_base_string = "POST&" + encodeURIComponent(base_url) + "&" + encodeURIComponent(req);
signing_key = CONFIG.TWITTER_CONSUMER_KEY_SECRET + '&' + AccessTokenSecret;
oauth_signature = encodeURIComponent(CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64));
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world'
}).then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
As a response, I get that:
UPDATE
considering that in my project I already have $cordovaOauthUtility I started using it this way:
function postTweet(accessToken, accessTokenSecret) {
var params, signature;
params = {
include_entities: true,
oauth_consumer_key: CONFIG.TWITTER_CONSUMER_KEY,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: accessToken,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
signature = $cordovaOauthUtility.createSignature('POST', 'https://api.twitter.com/1.1/statuses/update.json', params, { status: "hello" }, CONFIG.TWITTER_CONSUMER_KEY_SECRET, accessTokenSecret);
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: "hello"
}, {
headers: {
Authorization: signature.authorization_header
}
})
.then(function (response) {
return response;
}).catch(function (error) {
console.log(error);
});
}
UPDATE 2
After trying all the posibilities, the problem persist. Here I paste a plnkr where I have my code.
You are using crypto's HmacSHA256 but sending HMAC-SHA1 as the oauth_signature_method parameter which is the twitter one.
You should probably change your code to
oauth_signature = CryptoJS.HmacSHA1(signature_base_string, signing_key).toString(CryptoJS.enc.Base64);
If you look at your authorization header, you can also notice that something is wrong with it. Indeed, you can see that the oauth_nonce and the oauth_version are prefixed by a & sign, which shouldn't be the case and most likely mean to the api you are not specifying them. It probably comes from the fact you are using the same reqArray to construct both the signature and the header, or your code is not updated.
You also probably don't want to change the global headers sent from your app, in case another request is sent to another api at the same time. Rather, you should send this authorization header only for this specific xhr.
return $http.post('https://api.twitter.com/1.1/statuses/update.json', {
status: 'hello world',
}, {
headers: {
Authorization: auth,
},
})
Well, you're clearly adding oauth_token in your request array but it didn't show up in the screenshot? Is the AccessToken in the params undefined?
EDIT
According to the documentation, we must append double quotes to the headers. Try this?
reqArray = [
"include_entities=true",
'oauth_consumer_key="'+CONFIG.TWITTER_CONSUMER_KEY+'"',
'oauth_nonce="'+oauth_nonce+'"',
'oauth_signature_method="HMAC-SHA1"',
'oauth_timestamp="'+oauth_timestamp+'"',
'oauth_token="'+AccessToken+'"',
'oauth_version="1.0"',
'status='+encodeURIComponent("hello world")
];
Yikes.
I've downloaded your plnkr bundle and added a read only application key set. I only had to set up and make one change to get a {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."} response. Initially I was receiving {"errors":[{"code":32,"message":"Could not authenticate you."}]}.
Remove status: "hello" from between the curly brackets { } where you create your signature.
signature = $cordovaOauthUtility.createSignature('POST', 'https://api.twitter.com/1.1/statuses/update.json', params, { }, twitter.consumer_secret, twitter.access_token_secret);
My request headers become the following:
:authority:api.twitter.com
:method:POST
:path:/1.1/statuses/update.json
:scheme:https
accept:application/json, text/plain, */*
accept-encoding:gzip, deflate, br
accept-language:en-US,en;q=0.8
authorization:OAuth oauth_consumer_key="x",oauth_nonce="QFMmqiasFs",oauth_signature_method="HMAC-SHA1",oauth_token="y",oauth_timestamp="1496340853",oauth_version="1.0",oauth_signature="7Ts91LKcP%2FrYsLcF5WtryCvZQFU%3D"
content-length:18
content-type:application/json;charset=UTF-8
origin:http://localhost
referer:http://localhost/twits/
user-agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36
Googling eventually led me to a tutorial:
Displaying the Twitter Feed within Your Ionic App. I noted his general createTwitterSignature function does not take parameters and tweaked your code similarly.
function createTwitterSignature(method, url) {
var token = angular.fromJson(getStoredToken());
var oauthObject = {
oauth_consumer_key: clientId,
oauth_nonce: $cordovaOauthUtility.createNonce(10),
oauth_signature_method: "HMAC-SHA1",
oauth_token: token.oauth_token,
oauth_timestamp: Math.round((new Date()).getTime() / 1000.0),
oauth_version: "1.0"
};
var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, {}, clientSecret, token.oauth_token_secret);
$http.defaults.headers.common.Authorization = signatureObj.authorization_header;
}
I've read conflicting things about why there should/shouldn't be other parameters there, but I believe the signature is just supposed to be the basis of access and doesn't hash in every operation you want to perform - see Understanding Request Signing For Oauth 1.0a Providers.

Youtube API returns account details of a different user

I am using google's API for node.js
https://www.npmjs.com/package/googleapis
I am trying to get an array of all channels which belong to the person
who logged into my website with his google account.
I am using this scope for this matter:
''https://www.googleapis.com/auth/youtube.readonly'
Now here is part of my code:
app.get("/oauthcallback", function(req, res) {
//google redirected us back in here with random token
var code = req.query.code;
oauth2Client.getToken(code, function(err, tokens) { //let's check if the query code is valid.
if (err) { //invalid query code.
console.log(err);
res.send(err);
return;
}
//google now verified that the login was correct.
googleAccountVerified(tokens, res); //now decide what to do with it
});
});
function googleAccountVerified(tokens, res){ //successfully verified.
//user was verified by google, continue.
oauth2Client.setCredentials(tokens); //save tokens to an object
//now ask google for the user's details
//with the verified tokens you got.
youtube.channels.list({
forUsername: true,
part: "snippet",
auth: oauth2Client
}, function (err, response) {
if(err) {
res.send("Something went wrong, can't get your google info");
return;
}
console.log(response.items[0].snippet);
res.send("test");
});
}
Now, in this console.log:
console.log(response.items[0].snippet);
I am getting the same info, no matter what account I am using to log into my website:
{ title: 'True',
description: '',
publishedAt: '2005-10-14T10:09:11.000Z',
thumbnails:
{ default: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/1.jpg?v=51448e08' },
medium: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/mq1.jpg?v=51448e08' },
high: { url: 'https://i.ytimg.com/i/G9p-zLTq1mO1KAwzN2h0YQ/hq1.jpg?v=51448e08' } },
localized: { title: 'True', description: '' } }
if I do console.log(response) which is the entire response
I get:
{ kind: 'youtube#channelListResponse',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/ch97FwhvtkdYcbQGBeya1XtFqyQ"',
pageInfo: { totalResults: 1, resultsPerPage: 5 },
items:
[ { kind: 'youtube#channel',
etag: '"m2yskBQFythfE4irbTIeOgYYfBU/bBTQeJyetWCB7vBdSCu-7VLgZug"',
id: 'UCG9p-zLTq1mO1KAwzN2h0YQ',
snippet: [Object] } ] }
So, two problems here:
1) How do I get an array of owned channels by the logged user,
inside the array I need objects which will represent each channel and basic info like channel name, profile pic.
2) why am I getting the info of some random youtube channel called "True"
Not sure about question one but for question two you get the information for the channel called true because you are asking for it. forUsername: true
I would hope that once you correct this the response may contain more than one channel if the username has more than one.
Just a follow up to the question about basic info.
You dont use Youtube API to get an account's profile information. Instead, try Retrieve Profile Information with G+:
To retrieve profile information for a user, use the people.get API method. To get profile information for the currently authorized user, use the userId value of me.
JavaScript example:
// This sample assumes a client object has been created.
// To learn more about creating a client, check out the starter:
// https://developers.google.com/+/quickstart/javascript
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function(resp) {
console.log('Retrieved profile for:' + resp.displayName);
});
});
Google Sign-in for Websites also enables Getting profile information:
After you have signed in a user with Google using the default scopes, you can access the user's Google ID, name, profile URL, and email address.
To retrieve profile information for a user, use the getBasicProfile() method. For example:
if (auth2.isSignedIn.get()) {
var profile = auth2.currentUser.get().getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
}

How to access gmail API?

I generate my JWT, if my token is correct why dont work ? in Google Developers Console i enabled gmail plus youtube and other API, in credentials generate and download json
{
"private_key_id": "22dcf",
"private_key": "-----BEGIN PRIVATE KEY-----(remove)-----END PRIVATE KEY-----\n",
"client_email": "vgfjjc6#developer.gserviceaccount.com",
"client_id": "jc6.apps.googleusercontent.com",
"type": "service_account"
}
first generate token
var sHead=JSON.stringify({"alg":"RS256","typ":"JWT"});
var iat=timeStampf();
var exp=iat+3600;
var sPayload=JSON.stringify({
"iss":client_email,
"scope":scope,//gmail scope https://mail.google.com/
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":exp,
"iat":iat
});
var sJWS = KJUR.jws.JWS.sign("RS256", sHead,sPayload, private_key);
var paramstoken="grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-ty
pe%3Ajwt-bearer&assertion="+sJWS
getToken("POST","/oauth2/v3/token",paramstoken,jsonData,replier);
/*rest petition return 200 OK
{
"access_token" : "1bHLl5EOtu1pxz3fmmetKx9W8CV4t79M",
"token_type" : "Bearer",
"expires_in" : 3600
}*/
next i test my token
function testToken(accessToken,replier)
{
// /gmail/v1/users/me/messages /plus/v1/people/me
var client = vertx.createHttpClient().host(urlbase).port(443).ssl(true).maxPoolSize(10);
var request = client.request("GET", "/gmail/v1/users/me/messages", function(resp) {
console.log('server returned status code: ' + resp.statusCode());
console.log('server returned status message: ' + resp.statusMessage());
resp.bodyHandler(function(body) {
replier(JSON.parse(body.toString()));
});
});
request.headers()
.set("Content-type", contentType)
.set("Authorization", "Bearer "+accessToken);
request.end();
client.close();
}
if i use google+ scope and this petition the answer is 200 ok
https://www.googleapis.com/auth/plus.me /plus/v1/people/me
{
"kind":"plus#person",
"etag":"\"LR9iFZQGXELLHS07eQ\"",
"objectType":"person","id":"1149981343","displayName":"","name":{"familyName":"","givenName":""},"image":{"url":"https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50","isDefault":true},"isPlusUser":false,"language":"en_US","circledByCount":0,"verified":false}
but if i try with gmail
{"error":{"errors":[{"domain":"global","reason":"failedPrecondition","message":"Bad Request"}],"code":400,"message":"Bad Request"}}
In case of GMail, you are accessing a particular user's data, so when creating the JWT, you need to specify the user whom you are trying to impersonate, i.e. the user whose mailbox you want to access.
You can do this using the sub:"User's email address parameter" when forming the JWT Claim set
var sPayload=JSON.stringify({
"iss":client_email,
"sub":USER_EMAIL_ADDRESS
"scope":scope,//gmail scope https://mail.google.com/
"aud":"https://www.googleapis.com/oauth2/v3/token",
"exp":exp,
"iat":iat
});

Categories

Resources