not using curl
But following a node.js tutorial to build a sentiment analysis app for slack using IBM Watson tone analyzer. My process.env has already credentials from IBM like with the London instance url:
TONE_ANALYZER_IAM_APIKEY=<MY API KEY>
TONE_ANALYZER_URL=https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/c2f8238d-
cf7a-4184-9bc2-315e0a204d3a
The index.js
const ToneAnalyzerV3 = require('watson-developer-cloud/tone-analyzer/v3');
const toneAnalyzer = new ToneAnalyzerV3({
iam_apikey: process.env.TONE_ANALYZER_IAM_APIKEY,
url: 'https://api.eu-gb.tone-analyzer.watson.cloud.ibm.com/instances/c2f8238d-cf7a-4184-
9bc2-315e0a204d3a',
version: '2017-09-21',
I'm getting this error still
Error: Insufficient credentials provided in constructor argument. Refer to the documentation
for the required parameters. Common examples are username/password and iam_access_token.
at ToneAnalyzerV3.BaseService.initCredentials (/Users/qtn3118/sentimentapp/node_modules/ibm-
cloud-sdk-core/lib/base_service.js:243:23)
at ToneAnalyzerV3.BaseService (/Users/qtn3118/sentimentapp/node_modules/ibm-cloud-sdk-core/lib/base_service.js:98:29)
at ToneAnalyzerV3 [as constructor] (/Users/qtn3118/sentimentapp/node_modules/watson-developer-cloud/tone-analyzer/v3-generated.js:57:28)
at new ToneAnalyzerV3 (/Users/qtn3118/sentimentapp/node_modules/watson-developer-cloud/tone-analyzer/v3.js:34:23)
at Object.<anonymous> (/Users/qtn3118/sentimentapp/index.js:38:22)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
I tried with both API keys from "Manage" and "Service credentials" tabs from the IBM Watson dashboard - none of them work. Any one any ideas?
Try to use this way
Watson APIs Node.js SDK
import AssistantV1 from 'ibm-watson/assistant/v1';
import { IamAuthenticator } from 'ibm-watson/auth';
export const createAssistant = configs => new AssistantV1({
authenticator: new IamAuthenticator({ apikey: configs.apiKey }),
url: configs.url,
version: '2019-02-28'
});
More information about authentication is available in the SDK reference at https://cloud.ibm.com/apidocs/tone-analyzer?code=node#authentication
Related
I am trying to communicate with a web service. In order to do that, I need to encrypt a message using the public key that I received from the web service. The doc says the following about the public key format:
Format: X.509 encoded key in ANS.1 (sic!)
(ANS.1 is ASN.1 I guess).
The public key is:
-----BEGIN CERTIFICATE-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDE+ApyETIF1cXzKnU144P6lg/FcilmuQS2wBvaWp6t9OovthGmrsszd7eo4rL6Nitj1YOKETTtnwm4T+1EEyBrgwcfXAlm3FasTC/HIzhRRa+F8Yuz+UZkGvgP8Qa6B0vRob2BjhWx1PfwuWHQxGvAjiqUJ/dEMjocFuCrY5NZqwIDAQAB-----END CERTIFICATE-----
I tried to use this is a NodeJS code with the following:
const key = crypto.createPublicKey({
key: Buffer.from(publicKey),
format: 'der',
type: 'pkcs1'
});
But I received the following error:
node:internal/crypto/keys:607
handle.init(kKeyTypePublic, data, format, type, passphrase);
^
Error: error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag
at Object.createPublicKey (node:internal/crypto/keys:607:12)
at Object.<anonymous> (/XXXXXXXX/wsClient.js:16:20)
at Module._compile (node:internal/modules/cjs/loader:1149:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1203:10)
at Module.load (node:internal/modules/cjs/loader:1027:32)
at Module._load (node:internal/modules/cjs/loader:868:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47 {
opensslErrorStack: [
'error:0D09B00D:asn1 encoding routines:d2i_PublicKey:ASN1 lib',
'error:0D07803A:asn1 encoding routines:asn1_item_embed_d2i:nested asn1 error'
],
library: 'asn1 encoding routines',
function: 'asn1_check_tlen',
reason: 'wrong tag',
code: 'ERR_OSSL_ASN1_WRONG_TAG'
}
I can't even convert this public key using openssl into any usable format. The only way to see inside it for me was to use the following online tool:
https://lapo.it/asn1js/
Here I can at least see that the public key is valid, but I don't know how to use it in NodeJS. Converting it is also an accaptable solution for me.
After some painful hours it turns out that two things had to be done:
replace "BEGIN CERTIFICATE" with "BEGIN PUBLIC KEY" and the same for the end
They also needed to be in a separate line
After that NodeJS Crypto is able to parse the key.
Interestingly phpseclib was able to parse the key in the original format and then output it in the correct one, that's how I realized the solution.
I am trying to send a push notification from my nodejs app to my android app using firebase-admin
I followed the instructions as follows
import firebaseAdmin from 'firebase-admin';
import serviceAccount from '../../common/constants/pushKey.json';
firebaseAdmin.initializeApp({
credential: firebaseAdmin.credential.cert(serviceAccount),
});
and the pushKey is the json generated from
project settings -> service accounts -> firebase admin sdk -> generate new private key
However when calling
firebaseAdmin.messaging().sendToDevice(token, payload)
I get the following error
<TITLE>PROJECT_NOT_PERMITTED</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>PROJECT_NOT_PERMITTED</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
". Status code: 401.
at FirebaseMessagingError.<anonymous> (/Users/chris/Documents/ZebedeeApps/booty/node_modules/core-js/internals/wrap-error-constructor-with-cause.js:37:62)
at FirebaseMessagingError.Error (/Users/chris/Documents/ZebedeeApps/booty/node_modules/core-js/modules/es.error.cause.js:28:43)
at FirebaseMessagingError.FirebaseError [as constructor] (/Users/chris/Documents/ZebedeeApps/booty/node_modules/firebase-admin/lib/utils/error.js:44:28)
at FirebaseMessagingError.PrefixedFirebaseError [as constructor] (/Users/chris/Documents/ZebedeeApps/booty/node_modules/firebase-admin/lib/utils/error.js:90:28)
at new FirebaseMessagingError (/Users/chris/Documents/ZebedeeApps/booty/node_modules/firebase-admin/lib/utils/error.js:279:16)
at Object.createFirebaseError (/Users/chris/Documents/ZebedeeApps/booty/node_modules/firebase-admin/lib/messaging/messaging-errors-internal.js:57:12)
at /Users/chris/Documents/ZebedeeApps/booty/node_modules/firebase-admin/lib/messaging/messaging-api-request-internal.js:79:51
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errorInfo: {
code: 'messaging/authentication-error',
message: 'An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "<HTML>\n' +
'<HEAD>\n' +
'<TITLE>PROJECT_NOT_PERMITTED</TITLE>\n' +
'</HEAD>\n' +
'<BODY BGCOLOR="#FFFFFF" TEXT="#000000">\n' +
'<H1>PROJECT_NOT_PERMITTED</H1>\n' +
'<H2>Error 401</H2>\n' +
'</BODY>\n' +
'</HTML>\n' +
'". Status code: 401.'
},
codePrefix: 'messaging'
}
Any ideas?
Needs to enable Cloud Messaging API (Legacy) : https://stackoverflow.com/a/72901323/6890201
Firebase configuration
I've created a google cloud VM instance with neo4j on it, by following this instructions:
https://neo4j.com/docs/operations-manual/current/cloud-deployments/neo4j-gcp/single-instance-vm/
The browser Db looks fine: I can view and manipulate from the browser.
The problem is when trying connecting neo4j from nodejs using neo4j-driver npm.
I keep getting this error:
UnhandledPromiseRejectionWarning: Neo4jError: Connection was closed by server
this is the code:
const neo4j = require('neo4j-driver')
const uri = 'bolt://[EXTERNAL_IP]:[PORT]'
const user = 'USER_NAME'
const password = 'PASSWORD'
const createPerson = async () => {
const driver = neo4j.driver(uri, neo4j.auth.basic(user, password), { encrypted : "ENCRYPTION_OFF"})
const session = driver.session()
const personName = 'Bob'
try {
const result = await session.run(
'CREATE (a:Person {name: $name}) RETURN a',
{ name: personName }
)
const singleRecord = result.records[0]
const node = singleRecord.get(0)
console.log(node.properties.name)
} finally {
await session.close()
}
// on application exit:
await driver.close()
}
createPerson()
The code is taken from this link: https://neo4j.com/developer/javascript/
I run this command: gcloud compute ssh my-neo4j-instance in GCP shell, in hope that maybe adding ssh would solve the issue but it didn't.
changing the driver encrypted options to false also didn't help.
Console logging the error print this:
Neo4jError: Connection was closed by server
at captureStacktrace (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\node_modules\neo4j-driver\lib\result.js:263:15)
at new Result (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\node_modules\neo4j-driver\lib\result.js:68:19)
at Session._run (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\node_modules\neo4j-driver\lib\session.js:174:14)
at Session.run (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\node_modules\neo4j-driver\lib\session.js:135:19)
at createPerson (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\src\index.js:12:38)
at Object.<anonymous> (C:\Users\user\Desktop\Home Work\MyProject\LotteryService\src\index.js:31:1)
at Module._compile (internal/modules/cjs/loader.js:959:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Function.Module._load (internal/modules/cjs/loader.js:727:14) {
code: 'ServiceUnavailable',
name: 'Neo4jError'
what am i missing ?
EDIT 1:
I looked the google cloud logs. all i saw was logs for the start and stop of the vm.
Also, i fixed the code for the async function call in the main file.
so instead of the
createPerson();
i tried this:
(async() => {
console.log('before start');
await createPerson();
console.log('after start');
})();
still no good, still: Neo4jError: Connection was closed by server.
I also asked in neo4j blogs but got no answers.
EDIT 2:
I saw my issue in a different stack-overflow post. The answer there was to finish the logging to neo4j, by changing the password. but I already did that...
Also I joined the neo4j slack group but didn't got an answer still.
I'm trying to implement the DocuSign JWT Auth following this code example: https://github.com/docusign/eg-01-node-jwt/blob/master/lib/dsJwtAuth.js
But I get this error when calling requestJWTUserToken():
Error: Not initialised
at Sign.update (crypto.js:99:16)
at Object.sign (/code/node_modules/jwa/index.js:159:23)
at Object.jwsSign [as sign] (/code/node_modules/jws/lib/sign-stream.js:32:24)
at Object.module.exports [as sign (/code/node_modules/jsonwebtoken/sign.js:190:16)
at generateAndSignJWTAssertion (/code/node_modules/docusign-esign/src/ApiClient.js:63:16)
at exports.requestJWTUserToken (/code/node_modules/docusign-esign/src/ApiClient.js:892:19)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:73:53)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.getToken (/code/app/gateways/ConsentGateway.ts:64:16)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:54:41)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.checkToken (/code/app/gateways/ConsentGateway.ts:46:16)
at ConsentGateway.<anonymous> (/code/app/gateways/ConsentGateway.ts:139:24)
at Generator.next (<anonymous>)
at /code/app/gateways/ConsentGateway.ts:19:71
at new Promise (<anonymous>)
at __awaiter (/code/app/gateways/ConsentGateway.ts:15:12)
at ConsentGateway.getTemplateList (/code/app/gateways/ConsentGateway.ts:132:16)
at ConsentService.<anonymous> (/code/app/services/ConsentService.ts:58:50)
at Generator.next (<anonymous>)
at /code/app/services/ConsentService.ts:19:71
at new Promise (<anonymous>)
the code calling the method looks like this:
private async getToken(reqId: string): Promise<any> {
try {
const pathToPrivateKey = fs.readFileSync(path.resolve('/code/app/gateways/', 'test.pem'));
this.dsApiClient.setOAuthBasePath(this.authServer);
const jwtToken = await this.dsApiClient.requestJWTUserToken(
this.integrationKey, // clientId
this.guidAccountId, // userId
'signature',
pathToPrivateKey,
10 * 60
);
const expiresAt = moment().add(jwtToken.body.expires_in, 's');
return { accessToken: jwtToken.body.access_token, tokenExpirationTimestamp: expiresAt };
} catch (e) {
this.logger.error(
'Consent Error', reqId, ['accessToken'], { status: e.response.body.errorCode, message: e.response.body.message }
);
}
}
I cannot find any documentation for the requestJWTUserToken method which makes this error hard to debug.
Is there anyone familiar with the JWT Auth flow in node that could help out with this?
Here are the things that you must ensure:
You have an Integration key (clientID) that is configured correctly.
You have an RSA Private key. that key was copied/pasted exactly as given to your configuration file. New lines must be preserved
Your URLs are matching the environment. Meaning you use account-d and demo.docusign.net for the sandbox env endpoints.
You need the userId which is a GUid for the user that would be impersonated. That user must consent to the application. You have to ensure you pass userId and not accountId and that it is for the same account that you would be using.
If you confirm all of this and still get an error - I would consider to use our code example to start. I don't see code in your question, but our code example should be a good way to start.
I am following the tutorial Windows Azure SDK for Node.js - Compute Management to manage virtual machines.
I downloaded the pem file using azure account cert export to <Subscription GUID>.pem.
The script currently contains:
var subscriptionId ="<Subscription GUID>";
var pem = "<Subscription GUID>.pem";
var computeManagementClient = computeManagement.createComputeManagementClient(computeManagement.createCertificateCloudCredentials({
subscriptionId: subscriptionId,
pem: fs.readFileSync(pem)
}));
And when I run it from Node.js it produces the error:
C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\util\validate.js:416
throw new Error('Required argument ' + name + ' for function ' + func + ' is
^
Error: Required argument credentials.pem for function CertificateCloudCredentials is not defined
at throwMissingArgument (C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\util\validate.js:416:9)
at ArgumentValidator._.extend.string (C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\util\validate.js:426:7)
at C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\services\credentials\certificateCloudCredentials.js:35:9
at Object.validateArgs (C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\util\validate.js:478:3)
at new CertificateCloudCredentials (C:\Apps\azure\node_modules\azure-mgmt-compute\node_modules\azure-common\lib\services\credentials\certificateCloudCredentials.js:32:14)
at Object.exports.createCertificateCloudCredentials (C:\Apps\azure\node_modules\azure-mgmt-compute\lib\compute.js:54:10)
at Object.<anonymous> (C:\Apps\azure\setup.js:14:97)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
The issue is with pem: fs.readFileSync(pem). The SDK is not converting the node buffer to a string. There is an issue on Github.
Until this is fixed use toString on the buffer:
pem: fs.readFileSync(pem).toString()