Twillio accountsid and token issues - node.js

I am having trouble getting my token and account sid to work. i set them as constants in the file and the following error appears
Error:
throw 'Client requires an Account SID and Auth Token set explicitly ' +
^
Client requires an Account SID and Auth Token set explicitly or via the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables
const sid = xxxxxxxxxxx'
const tkn = 'xxxxxxxxxxx'
function Client(sid, tkn, host, api_version, timeout) {
//Required client config
if (!sid || !tkn) {
if (process.env.TWILIO_ACCOUNT_SID && process.env.TWILIO_AUTH_TOKEN) {
this.accountSid = process.env.TWILIO_ACCOUNT_SID;
this.authToken = process.env.TWILIO_AUTH_TOKEN;
}
else {
throw 'Client requires an Account SID and Auth Token set explicitly ' +
'or via the TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables';
}
}
else {
//if auth token/SID passed in manually, trim spaces
this.accountSid = sid.replace(/ /g, '');
this.authToken = tkn.replace(/ /g, '');
}
//Optional client config
this.host = host || defaultHost;
this.apiVersion = api_version || defaultApiVersion;
this.timeout = timeout || 31000; // request timeout in milliseconds
}

Twilio developer evangelist here.
You are setting sid and tkn as constants outside the Client function, however you also name the first two arguments passed into the function as sid and tkn. Within the scope of Client that means that sid and tkn are whatever you pass as arguments to the function.
My guess is that you are calling the Client function without any arguments and that leads to this error.
Rather than setting the sid and tkn in the file with the Client function, I recommend you pass them in as arguments when you call it.
const client = new Client(sid, tkn);
Let me know if that helps at all.

Related

Unable to Generate correct TOTP code from Twilio Authy App Node JS

Here is the scenrio, Id like to utilize https://npm.io/package/otplib to generate a TOTP code and verify it with the user input. The issue is that I am unable to generate a code using multiple authy apps that matches the one the totp.generate() generates. I think the issue might be either due to me passing an invalid secretKey format/type into totp.generate(). Or the issue might me due to the configuration of the totp component(maybe using the wrong encryption type(i.e sha2)) when compared to the authy app.
Here is my code sample following the guide from: https://npm.io/package/otplib
const generateSecretKey = (size=16) => {
const val = crypto.randomBytes(size).toString('hex').slice(0, size).toUpperCase()
return val;
}
const generateTotp = (secret) => {
const token = totp.generate(secret)
return token;
}
const authChallenge = (token, secret) =>{
const isValid = totp.check(token, secret);
return isValid
}
let secret = generateSecretKey()
console.log("secret => " + secret)
let token = generateTotp(secret)
console.log(`generateTotp => token ${token}`)
let authChallengeResponse = authChallenge(token, secret)
The returned value is
It seems the package is able to generate the code, the issue is it is not the same code as the ones in the authy app. Could this be due to me providing an invalid key type?

Post Go Live issue with Docusign using node.js

Here is my issue:
We integrated docusign in our application, server side with nodejs using this tutorial https://github.com/docusign/docusign-node-client ("OAuth JSON Web Token (JWT) Grant" section)
We have done the "Go Live Process": our application is registered in our production account
We have replaced the test config to the production config.
When we try to create an envelope, we get the following error:
PARTNER_AUTHENTICATION_FAILED: The specified Integrator Key was not found or is disabled. Invalid account specified for user
What am I doing wrong ?
async function docusignInit() {
var options;
var env = [40077,50077].indexOf(config.main.port) != -1 ? 'test' :'prod';
if (env == "test") {
options = {
basePath: restApi.BasePath.DEMO,
oAuthBasePath: oAuth.BasePath.DEMO
}
} else {
options = {
oAuthBasePath: "account.docusign.com",
// We called https://account.docusign.com/oauth/userinfo to found the uri
basePath:"https://eu.docusign.net/restapi/"
}
}
// in production, We must do
// var apiClient = new docusign.ApiClient(options.basePath);
// Otherwise, we get "Error: getaddrinfo ENOTFOUND undefined undefined:443"
var apiClient = new docusign.ApiClient(options.basePath);
var privateKeyFile = fs.readFileSync(`./server/docusign/keys/${env}/private.PEM`);
var res = await apiClient.requestJWTUserToken(config.docusign.integratorKey, config.docusign.userName, [oAuth.Scope.IMPERSONATION, oAuth.Scope.SIGNATURE], privateKeyFile, 3600)
var token = res.body.access_token;
apiClient.addDefaultHeader('Authorization', 'Bearer ' + token);
docusign.Configuration.default.setDefaultApiClient(apiClient);
await sendDocusign({
userId: 1,
firstName: 'foor',
lastName: 'bar',
email:'foo#bar;'
})
}
async function sendDocusign(role) {
var envDef = new docusign.EnvelopeDefinition();
envDef.emailSubject = 'Please signe this';
envDef.templateId = config.docusign.templateId;
var role = new docusign.TemplateRole();
role.roleName = "roleName";
role.clientUserId = role.userId;
role.name = role.firstName + " " + role.lastName;
role.email = role.email;
envDef.allowReassign = false;
envDef.templateRoles = [role];
envDef.status = 'sent';
var envelopesApi = new docusign.EnvelopesApi();
return await envelopesApi.createEnvelope(config.docusign.userAccountId, {
'envelopeDefinition': envDef
})
}
As you are able to generate AccesToken properly in PROD with PROD RSA KeyPair, so please check the endpoint which you using to make API calls to create an envelope. In demo it is always demo.docusign.net but in PROD it will be a different value depending on where you PROD account exists in the DocuSign data center. For instance if your PROD account is in NA1, then hostname will be will be www.docusign.net; if it is NA2 then hostname will be na2.docusign.net etc.
So it is recommended to make a /userinfo API call with the Access token to know the baseURI to make calls related to envelope. To get the base URI, call the /oauth/userinfo endpoint, supplying your application’s access token as a header.
For the developer sandbox environment, the URI is
https://account-d.docusign.com/oauth/userinfo
For the production environment, the URI is
https://account.docusign.com/oauth/userinfo
Documentation related to /userinfo API call is available here. Once you know you BaseURI then append this baseURI with envelopes related endpoint like below:
{base_uri} + "/restapi/v2.1/accounts/" + {account_id}
considering your error seems that you're missing the integratorKey or you're writing it in the wrontg way. According to that LINK is possible that you miss the brackets inside the intregrator key?
The integrator key must be placed in front of the user ID that is in
the Username node of the UsernameToken. The integrator key must be
wrapped with brackets, “[ and ]”.
An example of the api in the above documentation:
<soap:Header>
<wsa:Action>http://www.docusign.net/API/3.0/GetRecipientEsignList</wsa:Action>
<wsa:MessageID>uuid:3f9d7626-c088-43b4-b579-2bd5e8026b17</wsa:MessageID>
<wsa:ReplyTo>
<wsa:Address>http://schemas.xmlsoap.org/ws/2004/03/addressing/role/anonymous</wsa:Address>
</wsa:ReplyTo>
<wsa:To>http://demo.docusign.net/api/3.0/api.asmx</wsa:To>
<wsse:Security soap:mustUnderstand="1">
<wsu:Timestamp wsu:Id="Timestamp-8838aa24-9759-4f85-8bf2-26539e14f750">
<wsu:Created>2006-04-14T14:29:23Z</wsu:Created>
<wsu:Expires>2006-04-14T14:34:23Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-7c7b695e-cef7-463b-b05a-9e133ea43c41">
<wsse:Username>[Integrator Key Here]2988541c-4ec7-4245-b520-f2d324062ca3</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
<wsse:Nonce>SjlScsL5q3cC1CDWrcMx3A==</wsse:Nonce>
<wsu:Created>2006-04-14T14:29:23Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
</soap:Header>

How to get Implicit Grant Flow access_token

i'm useing Implicit Grant Flow. the problem is after the user grants access, Ican't accept Respond between redirects to redirect_uri. How can I know that granted access? and how to get the value of access_token?
Here's a complete code example of how to implement Implicit Grant flow:
// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
if (item) {
var parts = item.split('=');
initial[parts[0]] = decodeURIComponent(parts[1]);
}
return initial;
}, {});
window.location.hash = '';
// Set token
let _token = hash.access_token;
const authEndpoint = 'https://accounts.spotify.com/authorize';
// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
'user-read-birthdate',
'user-read-email',
'user-read-private'
];
// If there is no token, redirect to Spotify authorization
if (!_token) {
window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}
It grabs the hash of the URL and checks for an access token. If none is present, it redirects to Spotify authorization.
Here's a Glitch example that you can remix to get started: https://glitch.com/~spotify-implicit-grant
The access_token will be in the url hash of the redirect URL.
redirect_uri#access_token=
followed by the access token.
To get the access_token you just have to have the page you set as your redirect_uri parse the url and get the hash. The following js should do it:
function parseURLHash () {
var search = location.hash.substring(1);
var urlHash = search?JSON.parse('{"' + search.replace(/&/g, '","').replace(/=/g,'":"') + '"}',
function(key, value) { return key===""?value:decodeURIComponent(value) }):{}
return urlHash;
}
urlHash = parseURLHash();
var authToken = urlHash.access_token;

Can I add an expiry date to a customToken with Firebase v3?

I am in the process of migrating a node.js application to Firebase v3.
In v2 I was using FirebaseTokenGenerator to generate custom tokens. It requires an apiToken, which is inconsistent with the way that Firebase v3 works in node, and I see there is now a 'createCustomToken' method on the firebase.auth service so I am assuming that I should now use that.
The issue is that this method appears to accept only 'uid' and 'developerClaims' as parameters, where FirebaseTokenGenerator also accepted an options object which included an 'expires' attribute.
Is there a way to give the token generated by 'createCustomToken' an expiry date?
Update
Reference: https://groups.google.com/forum/#!topic/firebase-talk/Ezy3RDNNRAs
Once they login using the custom token, the Firebase exchanged Id
token is long lived and is automatically refreshed. You don't need to
mint a new custom token on each request. You can verify the Firebase
Id token using the backend server libraries and as long as it is
valid, you don't to sign in the user again.
So it looks like the generated token is temporary and used to retrieve an id token (internally) with
FIRAuth.auth()?.signInWithCustomToken(customToken)
From then on the client should be good.
With Firebase 3.0.4 Currently No.
From the nodejs module source code it looks like the jwt expiresIn is set at 1 hour. This is unacceptable for mobile app users (as long as they're logged in their key should be fine). Hope this is fixed asap since it blocks us from upgrading our sdk
FirebaseTokenGenerator.prototype.createCustomToken = function(uid, developerClaims) {
if (typeof uid !== 'string' || uid === '') {
throw new Error('First argument to createCustomToken() must be a non-empty string uid');
} else if (uid.length > 128) {
throw new Error('First argument to createCustomToken() must a uid with less than or equal to 128 characters');
} else if (typeof developerClaims !== 'undefined' && (typeof developerClaims !== 'object' || developerClaims === null || developerClaims instanceof Array)) {
throw new Error('Optional second argument to createCustomToken() must be an object containing the developer claims');
}
var jwtPayload = {};
if (typeof developerClaims !== 'undefined') {
jwtPayload.claims = {};
for (var key in developerClaims) {
/* istanbul ignore else */
if (developerClaims.hasOwnProperty(key)) {
if (BLACKLISTED_CLAIMS.indexOf(key) !== -1) {
throw new Error('Developer claim "' + key + '" is reserved and cannot be specified');
}
jwtPayload.claims[key] = developerClaims[key];
}
}
}
jwtPayload.uid = uid;
return jwt.sign(jwtPayload, this.serviceAccount.private_key, {
audience: FIREBASE_AUDIENCE,
expiresIn: ONE_HOUR_IN_SECONDS,
issuer: this.serviceAccount.client_email,
subject: this.serviceAccount.client_email,
algorithm: ALGORITHM
});
};
Update the below won't work due to this comment
"exp The time, in seconds, at which the token expires. It can be at a maximum 3600 seconds later than iat."
Firebase token max life span is 1 hour.
The solution appears to be generating our own token
Use a JWT library
You can create a custom token suitable for authenticating with Firebase by using any JWT creation library. Create a JWT that includes the following claims and is signed using RS256.
JWT claims
iss Your project's service account email address
sub Your project's service account email address
aud https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit
iat The current time, in seconds
exp The time, in seconds, at which the token expires. It can be at a maximum 3600 seconds later than iat.
uid The unique identifier of the signed-in user (must be a string, between 1-36 characters long)
claims (optional) Custom claims to include in the Security Rules auth variable.
An example of a token generating function that should meet the above criteria:
var ALGORITHM = 'RS256';
// List of blacklisted claims which cannot be provided when creating a custom token
var BLACKLISTED_CLAIMS = [
'acr', 'amr', 'at_hash', 'aud', 'auth_time', 'azp', 'cnf', 'c_hash', 'exp', 'iat', 'iss', 'jti',
'nbf', 'nonce'
];
var FIREBASE_AUDIENCE = 'https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit';
function generateFirebaseToken(serviceAccount, uid, expiresIn, developerClaims) {
var jwtPayload = {};
if (typeof developerClaims !== 'undefined') {
jwtPayload.claims = {};
for (var key in developerClaims) {
if (developerClaims.hasOwnProperty(key)) {
if (BLACKLISTED_CLAIMS.indexOf(key) !== -1) {
throw new Error('Developer claim "' + key + '" is reserved and cannot be specified');
}
jwtPayload.claims[key] = developerClaims[key];
}
}
}
jwtPayload.uid = uid;
return jwt.sign(jwtPayload, serviceAccount.private_key, {
audience: FIREBASE_AUDIENCE,
expiresIn: expiresIn,
issuer: serviceAccount.client_email,
subject: serviceAccount.client_email,
algorithm: ALGORITHM
});
}
Reference: firebase docs

Azure API App authentication

So I have an Azure API-App with protection working.
I want to use microsoftaccount and google as tokenname for GetRawTokenAsync.
How can I know before which token name to use? Can I obtain that from the current user info?
So something like:
var runtime = Runtime.FromAppSettings(Request);
var user = runtime.CurrentUser;
if (user == "google account") { // google account
var token = await user.GetRawTokenAsync("google");
}
else if (user == "microsoft account") { // microsoftaccount
var token = await user.GetRawTokenAsync("microsoftaccount");
}
Try adding .Result to the GetRawTokenAsync call
var runtime = Runtime.FromAppSettings(Request);
var user = runtime.CurrentUser;
TokenResult token = await user.GetRawTokenAsync("google").Result;
var name = (string)token.Claims["name"];

Resources