Skip to content

Instantly share code, notes, and snippets.

@moneal
Created August 23, 2017 02:21
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save moneal/af2d988a770c3957df11e3360af62635 to your computer and use it in GitHub Desktop.
Save moneal/af2d988a770c3957df11e3360af62635 to your computer and use it in GitHub Desktop.
Postman pre-request script to create a Firebase authentication JWT header.
/**
* This script expects the global variables 'refresh_token' and 'firebase_api_key' to be set. 'firebase_api_key' can be found
* in the Firebase console under project settings then 'Web API Key'.
* 'refresh_token' as to be gathered from watching the network requests to https://securetoken.googleapis.com/v1/token from
* your Firebase app, look for the formdata values
*
* If all the data is found it makes a request to get a new token and sets a 'auth_jwt' environment variable and updates the
* global 'refresh_token'.
*
* Requests that need authentication should have a header with a key of 'Authentication' and value of '{{auth_jwt}}'
*
* Currently the nested assertions silently fail, I don't know why.
*/
pm.expect(pm.globals.has('refresh_token')).to.be.true;
pm.expect(pm.globals.has('firebase_api_key')).to.be.true;
var sdk = require('postman-collection'),
tokenRequest = new sdk.Request({
url: 'https://securetoken.googleapis.com/v1/token',
method: 'POST',
body: {
mode: 'urlencoded',
urlencoded: [{
type: 'text',
key: 'key',
value: pm.globals.get('firebase_api_key')
},
{
type: 'text',
key: 'grant_type',
value: 'refresh_token'
},
{
type: 'text',
key: 'refresh_token',
value: pm.globals.get('refresh_token')
},
]
}
});
pm.sendRequest(tokenRequest, function(err, response) {
pm.test('request for access token was ok', function() {
pm.expect(response).to.be.ok();
});
const json = response.json();
pm.expect(json).to.an('object');
pm.test('response json has needed properties', function() {
pm.expect(json).to.have.own.property('access_token');
pm.expect(json).to.have.own.property('token_type');
pm.expect(json).to.have.own.property('refresh_token');
const accessToken = json.access_token;
const tokenType = json.token_type;
const refreshToken = json.refresh_token;
pm.environment.set('auth_jwt', tokenType + ' ' + accessToken);
pm.globals.set('refresh_token', refreshToken);
});
});
@Smith11b
Copy link

Smith11b commented Dec 22, 2019

Quick way to grab a refresh token in Node.js if you haven't built a front end that logs in. Create a token.js file.
Initialize a firebase app in it then call firebase auth and log the test user. the refresh token will be on the user response in the console. as follows. (Obv put your own keys and id's in firebaseconfig)

const firebase = require('firebase');
const firebaseConfig = {
    apiKey: process.env.FIREBASE_API_KEY,
    authDomain: process.env.FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.FIREBASE_DATABASE_URL,
    projectId: process.env.FIREBASE_PROJECT_ID,
    storageBucket: process.env.FIREBASE_STORAGE_URL,
    messagingSenderId: process.env.FIREBASE_MESSAGE_SENDER_ID,
    appId: process.env.FIREBASE_APP_ID,
    measurementId: process.env.FIREBASE_MEASUREMENT_ID
  };

firebase.initializeApp(firebaseConfig);

firebase.auth().signInWithEmailAndPassword(process.env.FIREBASE_TEST_USER_EMAIL, process.env.FIREBASE_TEST_USER_PASSWORD).then(user => {
    console.log(user);
})```

@fnovellafletcher
Copy link

Hi there!

Nice contribution, it's going to save our team dozens of hours!

Quick fix:
Line 45: pm.expect(response).to.be.ok();

  • POSTMAN tests log -> .to.be.ok() is not a function.
  • FIX: remove brackets ->. pm.expect(response).to.be.ok;

Thanks a lot!

@ekwus
Copy link

ekwus commented Nov 24, 2020

Hey

Do you know how to do this against the Authentication Emulator? I'm struggling to find how any of the Rest API url should be updated with locahost:9099

I want to be able to use

https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={API_KEY}

or

https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[API_KEY]

locally to test out my JWT implementation in the Firebase Functions calls.

Cheers

Dave

@rahulvyas
Copy link

How we can import this in postman app ?

@Bastianowicz
Copy link

thank you so much @moneal!
@rahulvyas copy and paste the script into Pre-Request Script of either your request or your whole collection. Thus the script will be run everytime you trigger the request and will provide you a valid jwt. Make sure to fix the test as suggested by @roboworski

You can also remove this piece tokenType + ' ' + of this line pm.environment.set('auth_jwt', tokenType + ' ' + accessToken);. You can then use {{auth_jwt}} as token of authorization method "bearer". This is especially helpful to inherit the authorization method to all requests within a collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment