OT_AUTHENTICATION_ERROR: Invalid token format (1004) - node.js

I am getting a 1004 error when trying to run the opentok api on the server, it is running fine on the localhost but when i ran the same code on the server, it gave me this opentok_authentication_error.
I have checked the apikey and serverkey multiple times and they both are correct, and the session id is also the same.
I can publish and subscribe sessions on the localhost, everything is working fine there but when i uploaded my website on the server and ran it their it gave me this error.
I've also checked the token value generated as well and it is the same which is being generated on the opentok website.
For frontend, I am using angular.js, I dont know what I am doing wrong and when it is working fine on localhost why is giving this error when running on a server.
server.js
Opentok = require('opentok');
var OTConfig = require('./config/otconfig');
var opentok = new Opentok(OTConfig.apiKey, OTConfig.secretKey);
var OT = require('./routes/opentok')(opentok, app);
routes/opentk.js
var OT_config = require('../config/dbconfig');
var express = require('express');
var router = express.Router();
module.exports = function(opentok, app) {
app.post('/opentok/join', function(req, res) {
var token,
sessionId = req.body.ot_session,
tokenOptions = {};
tokenOptions.role = "publisher";
tokenOptions.data = "username=" + req.body.name;
tokenOptions.data += "courseId=" + req.body.course;
tokenOptions.data += "role=" + req.body.role;
// Generate a token.
token = opentok.generateToken(sessionId, tokenOptions);
res.send(token);
});
}
controller.js
var opent = opentokService.generateToken(sessionId);
opent.then(function(data) {
$rootScope.token = data.data;
});
opentok service
return {
generateToken: function(id) {
let info = {
name: $rootScope.username,
id: id,
role: $rootScope.role,
ot_session: $rootScope.sessionId
}
return $http({
method: 'post',
url: '/opentok/join',
data: info
});
}
}

First, check your opentok account subscription is paused or not if it is paused then do the need full to activate your account.

Related

Unable to retrieve auth string from auth endpoint - received status: 500

I using react native and backend is node.I trying implement pusher in my app.
Object {
"error": "Unable to retrieve auth string from auth endpoint - received status: 0 from http://10.0.27.124:8070/pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users",
"status": 0,
"type": "AuthError",
}
Here is my react native code :
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
console.log(pusher)
const presenceChannel = pusher.subscribe('presence-channel');
Here is my node js code :
exports.authPusher = function (req, res) {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
console.log(req.body);
const presenceData = {
user_id: 'unique_user_id',
user_info: { name: 'Mr Channels', twitter_id: '#pusher' },
};
const auth = pusher.authenticate(socketId, channel, presenceData);
res.send(auth);
};
Thank you for answering.
I think you just forgot to use quote marks around authEndpoint parameter. Pusher is trying to call http instead of http://10.0.27.124:8070/pusher/auth.
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
If you open network tab on the web-developers toolbar of your browser, you must be able to see the actual request and debug it from there.

Hyperledger Composer module local_connection.json when deployed on Google Compute Engine

I have a hyperledger composer project that runs smoothly on localhost but I tried to deployed it to Google Cloud Compute Engine and does not work properly.
The project is divided in two parts: a composer network, and a nodejs backend to interact with the network. T
I followed the developer and deploy to single organization tutoriales from Composer site.
The nodejs server handles the registration and sign in logic and expose a rest api to interact with the client side. This is my code:
index.js
//post call to register graduate on the network
app.post('/api/registerGraduate', function(req, res) {
console.log("Creando cuenta graduado");
var graduateRut = req.body.graduaterut;
var cardId = req.body.cardid;
var firstName = req.body.firstname;
var lastName = req.body.lastname;
var email = req.body.email;
var phoneNumber = req.body.phonenumber;
network.registerGraduate(cardId, graduateRut, firstName, lastName, email, phoneNumber)
.then((response) => {
//return error if error in response
if (response.error != null) {
res.json({
error: response.error
});
} else {
//else return success
res.json({
success: response
});
}
});
});
network.js
registerGraduate: async function (cardId, graduateRut,firstName, lastName, email, phoneNumber) {
try {
//connect as admin
businessNetworkConnection = new BusinessNetworkConnection();
await businessNetworkConnection.connect('admin#degree');
//get the factory for the business network
factory = businessNetworkConnection.getBusinessNetwork().getFactory();
//create graduate participant
const graduate = factory.newResource(namespace, 'Graduate', graduateRut);
graduate.firstName = firstName;
graduate.lastName = lastName;
graduate.email = email;
graduate.phoneNumber = phoneNumber;
//add graduate participant
const participantRegistry = await businessNetworkConnection.getParticipantRegistry(namespace + '.Graduate');
await participantRegistry.add(graduate);
//issue identity
const identity = await businessNetworkConnection.issueIdentity(namespace + '.Graduate#' + graduateRut, cardId);
//import card for identity
await importCardForIdentity(cardId, identity);
//disconnect
await businessNetworkConnection.disconnect('admin#degree');
return true;
}
catch(err) {
//print and return error
console.log(err);
var error = {};
error.error = err.message;
return error;
}
},
I'm testing the rest api with postman. The error I'm getting back is "error": "Cannot find module './local_connection.json'" but that happens only the first time I send the post request. The second time the error is Error: Failed to add object with ID '166438715' in collection with ID 'Participant:org.degree.ucsd.University' as the object already exists.
Apparently despite the error is writing the data to the blockchain, but if I try to get the data I get an error stating that the cardid is not found.
So, what did I miss? If it works on localhost but not on a Google VM, is it the authentication? How can I solve this?
Thanks for your help!
EDIT!
importCardForIdentity function:
async function importCardForIdentity(cardName, identity) {
//use admin connection
adminConnection = new AdminConnection();
businessNetworkName = 'degree';
//declare metadata
const metadata = {
userName: identity.userID,
version: 1,
enrollmentSecret: identity.userSecret,
businessNetwork: businessNetworkName
};
//get connectionProfile from json, create Idcard
const connectionProfile = require('./local_connection.json');
const card = new IdCard(metadata, connectionProfile);
//import card
await adminConnection.importCard(cardName, card);
}
the 2nd error reported, is because (as you indicate), the participant is already created.
The real issue is trying to locate the newly issued 'graduateRut' business network card ('not found') from your client REST API or postman - in your current setup it would look for this on the same client under $HOME/.composer - is this on a different node to your nodeJS backend?
Also is your ImportCardForIdentity function something like shown here ?
Unable to issue identity card using Hyperledger Composer Javascript API

adding post to blogger nodejs

I have been trying to add post to blogger using api in nodejs. I get the success message but no title or content being added to the post. Just blank posts are being created. Here is my code:
var express = require('express');
var app = express();
var request = require('request');
var rp = require('request-promise');
const google = require ('googleapis');
const Youtube = require("youtube-api");
const blogger = google.google.blogger('v3')
, fs = require("fs")
, readJson = require("r-json")
, Lien = require("lien")
, Logger = require("bug-killer")
, opn = require("opn")
, prettyBytes = require("pretty-bytes")
;
// I downloaded the file from OAuth2 -> Download JSON
const CREDENTIALS = readJson('./bcreds.json');
// Init lien server
let server = new Lien({
host: "localhost"
, port: 6111
});
let oauth = Youtube.authenticate({
type: "oauth"
, client_id: CREDENTIALS.web.client_id
, client_secret: CREDENTIALS.web.client_secret
, redirect_url: CREDENTIALS.web.redirect_uris[0]
});
opn(oauth.generateAuthUrl({
access_type: "offline"
, scope: ["https://www.googleapis.com/auth/blogger"]
}));
// Handle oauth2 callback
server.addPage("/oauth2callback", lien => {
Logger.log("Trying to get the token using the following code: " + lien.query.code);
oauth.getToken(lien.query.code, (err, tokens) => {
if (err) {
lien.lien(err, 400);
return Logger.log(err);
}
Logger.log("Got the tokens.");
oauth.setCredentials(tokens);
lien.end("The post is being uploaded. Check out the logs in the terminal.");
// write below
blogger.posts.insert({
auth: oauth,
blogId: "blog id here",
resource: {
content: "postContent",
title: "postTitle",
},
}, function(err, success){
console.log(success);
});
// end
});
});
Please help in getting understand that where is the problem. The code runs correctly and it do add post but the post is just blank.

Sign in to Nodejs web app, using Azure AD

I'm trying to figure out how you can authenticate users using Azure AD. In order to experiment, I tried the example from Microsoft, found at https://github.com/Azure-Samples/active-directory-node-webapp-openidconnect.
I've set up an Active Directory in Azure, and added a new application called test with add id uri: http://testmagnhalv.
Now, when I run the server, following the instructions in the readme, I get redirected to login.microsoftonline.com and promted to log in. But when I provide username/pw, I get redirected back to the login page again.
I suspect the problem is that I don't set the variables in the config.json correctly, but I'm having a hard time finding documentation for what values need to be set.
Anyone got any experience with this example?
At first you must to add your app to active directory then use ADAL (Active Directory Authentication Library) for nodeJS
npm install adal-node
prepare your app for authentication referencing azure AD App registration values.
var AuthenticationContext = require('adal-node').AuthenticationContext;
var clientId = 'yourClientIdHere';
var clientSecret = 'yourAADIssuedClientSecretHere'
var redirectUri = 'yourRedirectUriHere';
var authorityHostUrl = 'https://login.windows.net';
var tenant = 'myTenant';
var authorityUrl = authorityHostUrl + '/' + tenant;
var redirectUri = 'http://localhost:3000/getAToken';
var resource = '00000002-0000-0000-c000-000000000000';
var templateAuthzUrl = 'https://login.windows.net/' +
tenant +
'/oauth2/authorize?response_type=code&client_id=' +
clientId +
'&redirect_uri=' +
redirectUri + '
&state=<state>&resource=' +
resource;
Now you need to get authorized with the token.
function createAuthorizationUrl(state) {
return templateAuthzUrl.replace('<state>', state);
}
// Clients get redirected here in order to create an OAuth authorize url and redirect them to AAD.
// There they will authenticate and give their consent to allow this app access to
// some resource they own.
app.get('/auth', function(req, res) {
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
res.cookie('authstate', token);
var authorizationUrl = createAuthorizationUrl(token);
res.redirect(authorizationUrl);
});
});
And finally handle the auth redirection
// After consent is granted AAD redirects here. The ADAL library is invoked via the
// AuthenticationContext and retrieves an access token that can be used to access the
// user owned resource.
app.get('/getAToken', function(req, res) {
if (req.cookies.authstate !== req.query.state) {
res.send('error: state does not match');
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(
req.query.code,
redirectUri,
resource,
clientId,
clientSecret,
function(err, response) {
var errorMessage = '';
if (err) {
errorMessage = 'error: ' + err.message + '\n';
}
errorMessage += 'response: ' + JSON.stringify(response);
res.send(errorMessage);
}
);
});
You can find the full example, and more here in ADAL for nodeJS repository:
Windows Azure Active Directory Authentication Library (ADAL) for Node.js
This is a simple but full demo taken from GitHub ADAL repository
website-sample.js
'use strict';
var express = require('express');
var logger = require('connect-logger');
var cookieParser = require('cookie-parser');
var session = require('cookie-session');
var fs = require('fs');
var crypto = require('crypto');
var AuthenticationContext = require('adal-node').AuthenticationContext;
var app = express();
app.use(logger());
app.use(cookieParser('a deep secret'));
app.use(session({secret: '1234567890QWERTY'}));
app.get('/', function(req, res) {
res.redirect('login');
});
/*
* You can override the default account information by providing a JSON file
* with the same parameters as the sampleParameters variable below. Either
* through a command line argument, 'node sample.js parameters.json', or
* specifying in an environment variable.
* {
* "tenant" : "rrandallaad1.onmicrosoft.com",
* "authorityHostUrl" : "https://login.windows.net",
* "clientId" : "624ac9bd-4c1c-4686-aec8-e56a8991cfb3",
* "clientSecret" : "verySecret="
* }
*/
var parametersFile = process.argv[2] || process.env['ADAL_SAMPLE_PARAMETERS_FILE'];
var sampleParameters;
if (parametersFile) {
var jsonFile = fs.readFileSync(parametersFile);
if (jsonFile) {
sampleParameters = JSON.parse(jsonFile);
} else {
console.log('File not found, falling back to defaults: ' + parametersFile);
}
}
if (!parametersFile) {
sampleParameters = {
tenant : 'rrandallaad1.onmicrosoft.com',
authorityHostUrl : 'https://login.windows.net',
clientId : '624ac9bd-4c1c-4686-aec8-b56a8991cfb3',
username : 'frizzo#naturalcauses.com',
password : ''
};
}
var authorityUrl = sampleParameters.authorityHostUrl + '/' + sampleParameters.tenant;
var redirectUri = 'http://localhost:3000/getAToken';
var resource = '00000002-0000-0000-c000-000000000000';
var templateAuthzUrl = 'https://login.windows.net/' + sampleParameters.tenant + '/oauth2/authorize?response_type=code&client_id=<client_id>&redirect_uri=<redirect_uri>&state=<state>&resource=<resource>';
app.get('/', function(req, res) {
res.redirect('/login');
});
app.get('/login', function(req, res) {
console.log(req.cookies);
res.cookie('acookie', 'this is a cookie');
res.send('\
<head>\
<title>FooBar</title>\
</head>\
<body>\
Login\
</body>\
');
});
function createAuthorizationUrl(state) {
var authorizationUrl = templateAuthzUrl.replace('<client_id>', sampleParameters.clientId);
authorizationUrl = authorizationUrl.replace('<redirect_uri>',redirectUri);
authorizationUrl = authorizationUrl.replace('<state>', state);
authorizationUrl = authorizationUrl.replace('<resource>', resource);
return authorizationUrl;
}
// Clients get redirected here in order to create an OAuth authorize url and redirect them to AAD.
// There they will authenticate and give their consent to allow this app access to
// some resource they own.
app.get('/auth', function(req, res) {
crypto.randomBytes(48, function(ex, buf) {
var token = buf.toString('base64').replace(/\//g,'_').replace(/\+/g,'-');
res.cookie('authstate', token);
var authorizationUrl = createAuthorizationUrl(token);
res.redirect(authorizationUrl);
});
});
// After consent is granted AAD redirects here. The ADAL library is invoked via the
// AuthenticationContext and retrieves an access token that can be used to access the
// user owned resource.
app.get('/getAToken', function(req, res) {
if (req.cookies.authstate !== req.query.state) {
res.send('error: state does not match');
}
var authenticationContext = new AuthenticationContext(authorityUrl);
authenticationContext.acquireTokenWithAuthorizationCode(req.query.code, redirectUri, resource, sampleParameters.clientId, sampleParameters.clientSecret, function(err, response) {
var message = '';
if (err) {
message = 'error: ' + err.message + '\n';
}
message += 'response: ' + JSON.stringify(response);
if (err) {
res.send(message);
return;
}
// Later, if the access token is expired it can be refreshed.
authenticationContext.acquireTokenWithRefreshToken(response.refreshToken, sampleParameters.clientId, sampleParameters.clientSecret, resource, function(refreshErr, refreshResponse) {
if (refreshErr) {
message += 'refreshError: ' + refreshErr.message + '\n';
}
message += 'refreshResponse: ' + JSON.stringify(refreshResponse);
res.send(message);
});
});
});
app.listen(3000);
console.log('listening on 3000');
https://github.com/AzureAD/azure-activedirectory-library-for-nodejs/blob/master/sample/website-sample.js
As I known, I suggest you can follow the two documents below as references to get start.
Web App Sign In & Sign Out with Azure AD https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-openidconnect-nodejs/
Integrating Azure AD into a NodeJS web application https://azure.microsoft.com/en-us/documentation/samples/active-directory-node-webapp-openidconnect/
For developing easier, you can try to use the node package passport-azure-ad(https://github.com/AzureAD/passport-azure-ad) that is the one strategy of passport (http://passportjs.org/) for NodeJS to implement your needs.
I had similar problem and able to resolve it. After googling i made two changes in config.js.
issuer value set to false.
responseMode value changed from query to form_post.
config.js :
exports.creds = {
issuer : false,
realm : "<TENANT>",
returnURL: 'http://localhost:3000/auth/openid/return',
identityMetadata: 'https://login.microsoftonline.com/common/.well-known/openid-configuration', // For using Microsoft you should never need to change this.
clientID: '<CLIENT_ID>',
clientSecret: '<CLIENT_SECRET>', // if you are doing code or id_token code
skipUserProfile: true, // for AzureAD should be set to true.
responseType: 'id_token code', // for login only flows use id_token. For accessing resources use `id_token code`
responseMode: 'form_post', // For login only flows we should have token passed back to us in a POST
};

How to keep node-dbox token between page refreshes in NodeJS/Express

Im trying to put together a little application using NodeJS, node-dbox and Express.
When requesting for DropBox authorization - it's a 3 step process, first need to get request_token, then user authorizes them visiting dropbox page, and only then request for access_token, based on request_token and the fact that user has authorized request.
However, by the time I served the page for step 1 and 2 (getting request_token, and providing user with url) - request_token instance is gone!, so in step 3 I can't request for an access_token, because it requires request_token being passed
I'm trying to save request_token in a cookie, but given that contains sensitive data, sending it to the client may not be such a good idea. Any ideas?
Simplified code is below:
(function() {
var dbox = require('dbox'),
config = require('easy-config'),
express = require('express'),
dboxApp = dbox.app(config.dropbox_credentials),
app = express();
app.use(express.cookieParser());
app.get('/', function(req, res) {
dboxApp.requesttoken(function(status, request_token) {
res.cookie('request_token', JSON.stringify(request_token));
res.send("<a href='" + request_token.authorize_url + "' targe='_new'>authorize via dropbox</a><br/>" + "<a href='/next'>next</a>");
});
});
app.get('/next', function(req, res) {
var request_token = JSON.parse(req.cookies.request_token);
if(request_token) {
dboxApp.accesstoken(request_token, function(status, access_token) {
var client = dboxApp.client(access_token);
client.account(function(status, reply){
res.send(reply);
});
});
} else {
res.send('sorry :(');
}
});
app.listen(3000);
})();
bonus question: client is created with access_token, so either instance of client or access_token need to be maintained across page refreshes as well, whats the best approach?
I managed to get it working by doing the following:
According to the Dropbox Developer reference you can provide a callback url by specifying it along with the request as stated here:
https://www.dropbox.com/developers/blog/20
https://www.dropbox.com/1/oauth/authorize?oauth_token=<request-token>&oauth_callback=<callback-url>
By storing the request token in the session and redirecting to the callback url you can then access the request token and be on your way.
A couple of Express route handlers, passed a member id as a parameter, to request and then handle the response might look like this:
linkAccount : function(req, res){
var memberId = req.params.memberId,
appKey = 'MYAPPKEY',
appSecret = 'MYAPPSECRET',
dbox = require('dbox'),
dboxApp = dbox.app({ "app_key": appKey, "app_secret": appSecret });
req.session.dboxStore = {};
req.session.dboxStore.dboxApp = dboxApp;
dboxApp.requesttoken(function(status, request_token){
req.session.dboxStore.request_token = request_token;
console.log("request_token = ", request_token);
res.redirect('https://www.dropbox.com/1/oauth/authorize?oauth_token='+request_token.oauth_token+
'&oauth_callback=http://myhost.local/linksuccess/dropbox/'+memberId);
res.end;
});
},
linkSuccess : function(req, res){
var memberId = req.params.memberId;
var appKey = 'MYAPPKEY';
var appSecret = 'MYAPPSECRET';
var dbox = require('dbox');
var dboxApp = dbox.app({ "app_key": appKey, "app_secret": appSecret });
var request_token = req.session.dboxStore.request_token;
dboxApp.accesstoken(request_token, function(status, access_token){
console.log('access_token = ', access_token);
Member.setAuthToken(memberId, 'dropbox', access_token, function(err, member){
res.render('index', { title:'SUCCESSFUL DROPBOX AUTH' });
res.end;
});
});
}

Resources