Facebook accountkit gives error when exchanging tokens from nodeJS server - node.js

I have been integrating fb AccounKit with my ionic application (NodeJS server). Front-end part has been done and I'm able to send and receive OTPs and success status.
But while getting client token from authorization code, I keep getting ""Error verifying the token in the \'access_token\'"' error. I followed the same procedure mentioned in their official docs.
This is my code :
var me_endpoint_base_url = 'https://graph.accountkit.com/v1.0/me';
token_exchange_base_url='https://graph.accountkit.com/v1.0/access_token';
var params = {
grant_type: 'authorization_code',
code: request.body.code,
access_token: app_access_token
};
}
// exchange tokens
console.log(Querystring.stringify(params))
var token_exchange_url = token_exchange_base_url + '?' + Querystring.stringify(params);
Request.get({url: token_exchange_url, json: true}, function(err, resp, respBody) {
console.log(respBody);
var view = {
user_access_token: respBody.access_token,
expires_at: respBody.expires_at,
user_id: respBody.id,
};
var me_endpoint_url = me_endpoint_base_url + '?access_token=' + respBody.access_token;
Request.get({url: me_endpoint_url, json:true }, function(err, resp, respBody) {
console.log(respBody);
if (respBody.phone) {
view.method = "SMS"
view.identity = respBody.phone;
} else if (respBody.email) {
view.method = "Email"
view.identity = respBody.email.address;
}
});
});
Please help?

When making a sever-to-server call to exchange a code for a token, you need to supply your Account Kit App Secret in the access token you're sending.
So the access token should look like:
'AA|{app_id}|{app_secret}'
For ex.
var app_access_token = ['AA', app_id, app_secret].join('|');
You can find your app secret from the Account Kit dashboard. Go on "Account Kit" page under products section of your app on developers.facebook.com and click on the "Show" button next to the box for "Account Kit App Secret" to see your app secret.
Also remember that you should never include your app secret on any javascript code that runs on the client side. This secret is to be used only from your server-side node.js code and no one else should be able to see it

Related

Invalid token generating from service-principal and secret based login method

Configured service principal and trying to use the token received from the method to hit customer insights API.
https://api.ci.ai.dynamics.com/v1/instances/{instanceId}/profilestore/stateinfo
Above API requires bearer token as header for authorization.
Token receiving from auth response is invalid and not accepting by Customer Insights API.
msRestNodeAuth.loginWithServicePrincipalSecretWithAuthResponse(clientId, secret,
tenantId).then((authres) => {
console.dir(authres, { depth: null })
}).catch((err) => {
console.log(err);
});
Also, tried the another method of getting access token using this endpoint
Still the token we are receiving are not getting accepted by customer insights.
'https://login.microsoftonline.com/'tenantid'/oauth2/v2.0/token';
Try to follow this article: https://learn.microsoft.com/en-us/dynamics365/customer-insights/audience-insights/apis
If you request the token with client credentials flow, it's need to add the application permission.
You could test in Postman using the scope(resource) https://azurecustomerinsights.com/.
POST https://login.windows.net/{tenant-id}/oauth2/token
Content-Type: application/x-www-form-urlencoded
client_id={}
&resource=https://azurecustomerinsights.com/
&client_secret={}
&grant_type=client_credentials
Server to Server via Client Credentials, see here:
var adal = require('adal-node').AuthenticationContext;
var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant';
var authorityUrl = authorityHostUrl + '/' + tenant;
var clientId = 'yourClientIdHere';
var clientSecret = 'yourAADIssuedClientSecretHere'
var resource = 'https://azurecustomerinsights.com/';
var context = new AuthenticationContext(authorityUrl);
context.acquireTokenWithClientCredentials(resource, clientId, clientSecret, function(err, tokenResponse) {
if (err) {
console.log('well that didn\'t work: ' + err.stack);
} else {
console.log(tokenResponse);
}
});

Node JS & Auth0 | Get profile

Hey developer friends,
I'm building a small alexa skill & use auth0 as the authentication system. Now I want to get the userinfo/profile of the user, because I need the userId. In the request from alexa is an an accessToken. With that token, I want to be able to get the information from auth0.
var AuthenticationClient = require('auth0').AuthenticationClient;
var auth0 = new AuthenticationClient({
domain: '[MY NAME].eu.auth0.com',
clientId: '[MY CLIENT ID]',
clientSecret: '[MY CLIENT SECRET]'
});
Then in the actual function:
const access_token = session.user.accessToken;
console.log("ACCESSTOKEN:", access_token)
auth0.getProfile(access_token, function (err, userInfo) {
if(err) {
console.log("failed to retrieve profile", err)
} else {
const userId = JSON.parse(userInfo)['sub'];
console.log(userId);
}
}
When I run the code, I get the error 401 Unauthorized from auth0, although I use the provided accessToken. The accessToken is something like this in the amazon request: "VDMj7VBJ0EaJ1XZhvVRUfPgYNtxviro"
Any suggestions on how to do that properly?
I initalized the auth module twice, fixed it & now it works fine!

node-oauth Yahoo API oAuth2 issue

I'm building an app with node.js and express.js. I'm using the node-oauth module to connect to yahoo so I can make get requests to the api. I keep getting the error below
{ statusCode: 401,
data: '{"error":{"#lang":"en-US",
"#uri":"http://yahoo.com",
"description":"Not Authorized - Either YT cookies or a valid OAuth token must be passed for authorization","detail":"Not Authorized - Either YT cookies or a valid OAuth token must be passed for authorization"}}' }
After trying for a while to figure out my problem, I'm asking the community to check out my code and see what I am doing wrong. Code included below.
"use strict";
// declare libraries
var express = require('express');
var router = express.Router();
var OAuth = require('OAuth');
// set yahoo key and secret
var yahooKey = '*****************************************************';
var yahooSecret = '*********************************';
var oauth2 = new OAuth.OAuth2(
yahooKey,
yahooSecret,
'https://api.login.yahoo.com/',
'oauth2/request_auth',
'oauth2/get_token',
null
);
router.get('/', function(req, res, next) {
var access_token = oauth2.getOAuthAccessToken(
'',
{'grant_type':'authorization_code', 'redirect_uri':'http://www.domain.com'},
function (e, access_token, refresh_token, results) {
// console.log(e);
// done();
});
// console.log(oauth);
oauth2.get(
'https://social.yahooapis.com/v1/user/circuitjump/profile?format=json',
access_token,
function (error, data, response){
if (error) {
console.error(error);
}
// data = JSON.parse(data);
// console.log(JSON.stringify(data, 0, 2));
// console.log(response);
});
res.render('index', { title: 'Express' });
});
// export route
module.exports = router;
Any help is greatly appreciated. My brain is fried ...
You seem to be missing some steps. I would direct you first to this guide:
https://developer.yahoo.com/oauth2/guide/flows_authcode/
First, from your starting path at '/', you need to redirect (302) the user to an authorization page (Step 2 of yahoo's guide). The oauth lib has a helper for you to generate the correct URL:
var location = oauth2.getAuthorizeUrl({
client_id: yahooKey,
redirect_uri: 'https://yourservice.com/oauth2/yahoo/callback',
response_type: 'code'
});
res.redirect(location);
What you just did there is you redirected the user's browser to yahoo's authorization page, where the user gets a dialog asking if they want to allow your service XYZ access to do stuff on the user's behalf. Upon clicking "Allow", yahoo will redirect the browser to your callback url (Step 3 of yahoo's guide), providing you with an authorization code in the query params. In this example you have hooked up at /oauth2/yahoo/callback
You can set that up like so (Step 4 of yahoo's guide):
router.get('/oauth2/yahoo/callback', function(req, res) {
// Aha now I have an authorization code!
var code = req.query.code;
oauth2.getOAuthAccessToken(
code,
{
'grant_type': 'authorization_code',
'redirect_uri': 'oob'
},
function(e, access_token, refresh_token, results) {
console.log('Now I have a token', access_token, 'that I can use to call Yahoo APIs!');
res.end();
});
});
I hope all of that makes some sense. I'll leave it as an exercise for you to figure out the refresh token (step 5). If you make it this far, that part should be easy :)
Edit
It looks like Yahoo also requires you to send your key and secret in a Authorization Basic header. You can generate this header and tell the oauth2 module to include it like so:
var encoded = new Buffer(yahooKey+":"+yahooSecret).toString('base64')
var authHeader = "Basic " + encoded;
var oauth2 = new OAuth.OAuth2(
yahooKey,
yahooSecret,
'https://api.login.yahoo.com/',
'oauth2/request_auth',
'oauth2/get_token',
{ Authorization: "Basic " + authHeader}
);

Video upload using youtube/google API directly from server using node.js?

I am trying to upload videos from server without any manual authentication by user in the client side . I tried the below code snippet for video upload but it authenticates the user in the browser and asks for the acceptance of the app.
var ResumableUpload = require('node-youtube-resumable-upload');
var googleauth = require('google-auth-cli');
var google = require('googleapis');
var getTokens = function(callback) {
googleauth({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/youtube.upload' //can do just 'youtube', but 'youtube.upload' is more restrictive
},
{ client_id: CLIENT_ID, //replace with your client_id and _secret
client_secret: CLIENT_SECRET,
port: 3000
},
function(err, authClient, tokens) {
console.log(tokens);
callback(tokens);
});
};
getTokens(function(result) {
tokens = result;
upload();
});
var upload = function() {
var metadata = {snippet: { title: 'title', description: 'Uploaded with ResumableUpload' },
status: { privacyStatus: 'public' }};
var resumableUpload = new ResumableUpload(); //create new ResumableUpload
resumableUpload.tokens = tokens;
resumableUpload.filepath = 'youtube/test4.mp4';
resumableUpload.metadata = metadata;
resumableUpload.monitor = true;
resumableUpload.eventEmitter.on('progress', function(progress) {
console.log(progress);
});
resumableUpload.initUpload(function(result) {
console.log(result);
return;
});
}
But for my app it should directly upload the video to youtube from the server. For that I need the access token and refresh token I tried lot to get the access token directly but I couldn't able to get it.
So any help or idea to how to make the video upload directly from server to a channel account. I searched lot in google for a node module to do that but I couldn't able to find it.
I have been using this approach to upload video
Getting the web based generated token using the client library.
Getting the youtube upload permission from user for my application &
access_type=offline.
Access type offline gives refresh token in response. This token
will help to continue upload from backend server token when its
expires.
After getting the permission. It will redirect to URL with code.
Using the given code generate access_token
Save this token for future use.
Use the same token to push the video from your server to youtube
server
Refresh the token when it expires.
But is there any way to implement this approach without getting the youtube upload permission from user for my application.
You can do server side authetication using google API(JWT) with "Service Account". But direct upload from your server to youtube server without user permission is not possible. For uploading the video google needs OAuth2.0 authentication. It will give you error unAuthorized(401)- youtubeSignupRequired with "Service Account" using JWT authentication.
Becuase of the above limitation. You have use below Approach to work with this is-
Get the web based generated token using the client library.
Get the youtube upload permission from user for your application & access_type=offline.
Access type offline gives you refresh token in response. This token will help you to continue upload from backend server token when its expires.
After getting the permission. It will redirect to URL with code.
Using the given code generate access_token
Save this token for future use.
Use the same token to push the video from your server to youtube server
Refresh the token when it expires. And follow the step 3 - 5 again.
Currently this is the only way to upload the video on youtube.
Added the code on git repository nodejs-upload-youtube-video-using-google-api
For why its not possible? Check the below reference link & code:
From google API Doc: This error is commonly seen if you try to use the OAuth 2.0 Service Account flow. YouTube does not support Service Accounts, and if you attempt to authenticate using a Service Account, you will get this error. You can check all the error code & its detail using link: YouTube Data API - Errors
From gadata Issues: Youtube v3 Google Service Account Access
From google blog spot:List of Google API supported using Service Account
Check below code to get access_token from server side
You can check it yourself using below steps & code:
Go to Google Developer Console
Create Project
To Get Google+ API Access go to: APIs & Auth->APIs ->enable YouTube Data API v3
To Enable Service Account go to: APIs & Auth->Credentials->Create new Client ID->Click on Service Account->Create Client Id
Save the secret file on your system & keep it secure.
Create the secret key using below command & file you have downloaded:
openssl pkcs12 -in /home/rajesh/Downloads/Yourkeyfile.p12 -out youtube.pem -nodes
- Enter password: ***notasecret***
6. You can authorize & access api from server side as below:
var google = require('googleapis');
var authClient = new google.auth.JWT(
'Service account client email address', #You will get "Email address" in developer console for Service Account:
'youtube.pem', #path to pem file which we create using step 6
null,
['https://www.googleapis.com/auth/youtube.upload'],
null
);
authClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
console.log(tokens);
});
Get youtube video list using Service Account(working):
var google = require('googleapis');
var youtube = google.youtube('v3');
var authClient = new google.auth.JWT(
'Service account client email address', #You will get "Email address" in developer console for Service Account:
'youtube.pem',
null,
['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
null
);
authClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
youtube.videos.list({auth:authClient,part:'snippet',chart:'mostPopular'}, function(err, resp) {
console.log(resp);
console.log(err);
});
});
Insert youtube video using Service Account and googleapis module:
var google = require('googleapis');
var youtube = google.youtube('v3');
var authClient = new google.auth.JWT(
'Service account client email address', #You will get "Email address" in developer console for Service Account:
'youtube.pem',
null,
['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
null
);
authClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
youtube.videos.insert({auth:authClient,part:'snippet,status,contentDetails'},function(err,resp)
console.log(resp);
console.log(err);
});
});
Insert/Upload API Returned below Error:
{ errors:
[ { domain: 'youtube.header',
reason: 'youtubeSignupRequired',
message: 'Unauthorized',
locationType: 'header',
location: 'Authorization' } ],
code: 401,
message: 'Unauthorized' }
Insert youtube video using Service Account and ResumableUpload module:
var google = require('googleapis');
var ResumableUpload = require('node-youtube-resumable-upload');
var authClient = new google.auth.JWT(
'Service account client email address', #You will get "Email address" in developer console for Service Account:
'youtube.pem',
null,
['https://www.googleapis.com/auth/youtube','https://www.googleapis.com/auth/youtube.upload'],
null
);
authClient.authorize(function(err, tokens) {
if (err) {
console.log(err);
return;
}
var metadata = {snippet: { title: 'title', description: 'Uploaded with ResumableUpload' },status: { privacyStatus: 'private' }};
var resumableUpload = new ResumableUpload(); //create new ResumableUpload
resumableUpload.tokens = tokens;
resumableUpload.filepath = 'youtube.3gp';
resumableUpload.metadata = metadata;
resumableUpload.monitor = true;
resumableUpload.eventEmitter.on('progress', function(progress) {
console.log(progress);
});
resumableUpload.initUpload(function(result) {
console.log(result);
return;
});
});
Insert/Upload API Returned below Error:
{ 'www-authenticate': 'Bearer realm="https://accounts.google.com/AuthSubRequest", error=invalid_token',
'content-type': 'application/json; charset=UTF-8',
'content-length': '255',
date: 'Tue, 16 Sep 2014 10:21:53 GMT',
server: 'UploadServer ("Built on Aug 18 2014 11:58:36 (1408388316)")',
'alternate-protocol': '443:quic,p=0.002' }
Screen shot attached for "How to get google key?"
Conclusion: Uploading a video without user permission is not possible.

Google Play Android Developer API 401 Insufficient permissions

I'm using Google Play Android Developer API to server to server check subscription status of our users' subscriptions but after successful authorization and asking for an existing subscription I get the 401 response with the following message 'The current user has insufficient permissions to perform the requsted operation'.
Visiting https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=XXXXXX I can see that I do have the requested scope (https://www.googleapis.com/auth/androidpublisher) but I still get the same response everytime.
Did anyone else have the same problem?
Edit: I've seen what the Explore API app does, it adds the key in the query string of a request but I don't have that value. In the console I've created a Service Account Client Id which has a client id, email address and a private key but there is no API key which apparently Explore API uses.
Edit no. 2: I've added the service account generated email both to Google Play Developer Console and Google Wallet console but I still have no acces. I'm using nodejs and the google-oauth-jwt because there is not google provided lib for nodejs.
Here is the code I'm using to make a request:
var request = require('google-oauth-jwt').requestWithJWT();
function makeReq() {
request({
url: 'https://www.googleapis.com/androidpublisher/v1.1/applications/{packageName}/subscriptions/{subscriptionId}/purchases/{purchaseToken}',
jwt: {
// use the email address of the service account, as seen in the API console
email: 'blahblahtrutjtrutj#developer.gserviceaccount.com',
// use the PEM file we generated from the downloaded key
keyFile: 'purchases-test.pem',
// specify the scopes you wish to access
scopes: ['https://www.googleapis.com/auth/androidpublisher']
}
}, function (err, res, body) {
if (err) {
console.log(err);
} else {
console.log("BODY IS ------------------------------------------");
console.log(JSON.parse(body));
}
});
}
If your app is only released in a closed alpha track, you'll also have to add your service account's email address (client_email) to the License Testers at Settings -> Account detail in the Play Console.
There is an email address associated with your service account.
This needs to have appropriate permissions in both the dev console AND the Play store. Make sure to add the service address to the Play store.
The way I approached it was to use
var googleAuth = require('google-oauth-jwt'),
authObject = {
email: 'blahblahtrutjtrutj#developer.gserviceaccount.com',
keyFile: 'purchases-test.pem',
scopes: ['https://www.googleapis.com/auth/androidpublisher']
};
googleAuth.authenticate(authObject, function (err, token) {
next(err, token);
});
I store the token in redis for an hour and use that token to make my request to the store:
var opts = {
url : verifyUrl + payload.packageName + '/inapp/' + payload.productId + '/purchases/' + payload.token,
headers: {
authorization : 'Bearer ' + token
}
};
request.get(opts, function (error, response, body) {
next(error, response, body);
});

Resources