Created
March 16, 2017 19:57
-
-
Save nsantorello/b6e040c00d3f0d3f2802279d5bfb145e to your computer and use it in GitHub Desktop.
Service-to-Service Authentication with Cloud Endpoints
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Step 1: Generate the request token | |
var jwt = require('jsonwebtoken'); | |
var key = require('./key'); // path to service account JSON file | |
var SERVICE_ID = '...'; // this is the 'host' proprety of the service management's openapi.yaml | |
var now = Math.floor(Date.now() / 1000); | |
var payload = { | |
iat: now, // issued right now | |
exp: now + 3600, // expire after 1 hour | |
iss: key.client_email, | |
target_audience: 'https://' + SERVICE_ID, | |
aud: 'https://www.googleapis.com/oauth2/v4/token' | |
}; | |
var token = jwt.sign(payload, key.private_key, { algorithm: 'RS256'}); | |
// Step 2: Request the ID token from Google | |
var qs = require("querystring"); | |
var http = require("https"); | |
var options = { | |
"method": "POST", | |
"hostname": "www.googleapis.com", | |
"port": null, | |
"path": "/oauth2/v4/token", | |
"headers": { | |
"content-type": "application/x-www-form-urlencoded", | |
"cache-control": "no-cache" | |
} | |
}; | |
var req = http.request(options, function (res) { | |
var chunks = []; | |
res.on("data", function (chunk) { | |
chunks.push(chunk); | |
}); | |
res.on("end", function () { | |
var body = Buffer.concat(chunks); | |
console.log(body.toString()); | |
}); | |
}); | |
req.write(qs.stringify({ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', | |
assertion: token })); | |
req.end(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "test-gauth", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"jsonwebtoken": "^7.3.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment