Monday, 9 July 2018

Node.js Oauth2 service authentication using JWT

[Question]STATUS: unsolvedI am a beginner to Node and am trying to create a microservice to route API calls between google's Dialogflow and a company backend server. I believe that in order to make API calls to edit intents etc I need an Oauth2 access token but I am stuck trying to acquire the token.I am currently using the following jwt-generator.js from https://www.jwt.io to create a JWT:// Using CryptoJS library const CryptoJS = require("crypto-js") // Defining our token parts var header = { "alg": "RS256", "typ": "JWT" }; var claimSet = { "iss": "dialogflow-iprbag@PROJETID.iam.gserviceaccount.com", "scope": "google.cloud.dialogflow/", "aud": "https://ift.tt/1GDfmSD", "exp": Math.floor(Date.now()/1000) + 3600, "iat": Math.floor(Date.now()/1000) }; var secret = "-----BEGIN PRIVATE KEY-----blahblahblah-----END PRIVATE KEY-----\n"; function base64url(source) { // Encode in classical base64 encodedSource = CryptoJS.enc.Base64.stringify(source); // Remove padding equal characters encodedSource = encodedSource.replace(/=+$/, ''); // Replace characters according to base64url specifications encodedSource = encodedSource.replace(/\+/g, '-'); encodedSource = encodedSource.replace(/\//g, '_'); return encodedSource; } var stringifiedHeader = CryptoJS.enc.Utf8.parse(JSON.stringify(header)); var encodedHeader = base64url(stringifiedHeader); var stringifiedClaimSet = CryptoJS.enc.Utf8.parse(JSON.stringify(claimSet)); var encodedClaimSet = base64url(stringifiedClaimSet); var signature = stringifiedHeader + "." + stringifiedClaimSet; signature = CryptoJS.HmacSHA256(signature, secret); signature = base64url(signature); console.log(encodedHeader + "." + encodedClaimSet + "." + signature); I am then sending the generated JWT to the Oauth2 token server in a POST request with the following token-get.js node script:const request = require('request') var formData = { "grant_type": "urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer", "assertion": JWT_HERE, "Content-Type": "application/x-www-form-urlencoded" } request.post({url:'https://ift.tt/1GDfmSD', formData: formData}, function(req, err, res) { console.log(res) }) It is my understanding that the grant_type header is constant but when I test this request in postman I get an invalid grant_type error. When I run the token-get.js I get an unsupported dataForm error.Honestly I am quite lost, if anyone is experienced in this topic please let me know!Thanks

Submitted July 09, 2018 at 10:36AM by SebbyGotGame

No comments:

Post a Comment