-
-
Save aszx87410/0e938feaf2984bde975649679af1aec3 to your computer and use it in GitHub Desktop.
Postman pre-request script to create a Firebase authentication JWT header.
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
/** | |
* 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); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment