Skip to content

Instantly share code, notes, and snippets.

@memes
Last active May 12, 2018 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save memes/25890badc889450f762b6ceb9a7d7989 to your computer and use it in GitHub Desktop.
Save memes/25890badc889450f762b6ceb9a7d7989 to your computer and use it in GitHub Desktop.
Google Cloud IoT authentication for Postman
// Keep jsrsasign libs assume they are working in a browser; fake these out..
var navigator = {
appName: "Cloud IoT test script"
};
var window = {};
// Make sure that jsrsasign is in scope
eval(postman.getEnvironmentVariable('jsrsasign'));
// Cloud IoT HTTP URL is of form: https://cloudiotdevice.googleapis.com/v1/projects/{project-id}/locations/{location}}/registries/{registry}/devices/{device-id}/...
var audience = request.url.match(/.*\/v1\/projects\/([^\/]+)\/locations\/.*/)[1];
if (audience == "{{projectId}}") {
audience = postman.getEnvironmentVariable("projectId");
}
var iat = Math.floor(Date.now() / 1000);
var ttl = parseInt(postman.getEnvironmentVariable("jwtTTL") || "60");
var privKey = postman.getEnvironmentVariable("rsaPrivKey");
var authToken = KJUR.jws.JWS.sign(null, { 'alg': 'RS256', 'typ': 'JWT' }, { 'iat': iat, 'exp': iat + ttl, 'aud': audience}, privKey);
postman.setEnvironmentVariable("authToken", authToken);
// Add this as test script for GET https://cdnjs.cloudflare.com/ajax/libs/jsrsasign/8.0.4/jsrsasign-all-min.js
// to retrieve and add jsrsasign library to postman requests
postman.setEnvironmentVariable('jsrsasign', responseBody);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment