Farhan Chauhan
Farhan Chauhan

Reputation: 585

Get Firebase Access Token in POSTMAN

In my web application, I am using Firebase for Authentication, to access any API, I have to authenticate from firebase.

Question: How can I get access token of firebase in Postman?

I have 2 solutions for this problem:

1) Get Access Token from firebase in postman, store that access token in postman global env. variable and then I can do other API request. (Here I don't know how to get access token in postman)

2) Do the login in the browser, copy access token from network request, store it in bash_profile and then use it in Postman. (Here I don't know how to read OS env. variable)

Upvotes: 40

Views: 37940

Answers (10)

Leo
Leo

Reputation: 409

go to the pre-request script and add this code (use your API_KEY, USER_EMAIL, USER_PASSWORD)

  const reqObject = {
    url: "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={API_KEY}", // API_KEY -> your API key from firebase config 
    method: 'POST',
    header: 'Content-Type:application/json',
    body: {
        mode: 'raw',
        raw: JSON.stringify({ "email": {USER_EMAIL}, "password": {USER_PASSWORD}, "returnSecureToken": true })
    }
};

pm.sendRequest(reqObject, (err, res) => {
    const idToken = res.json().idToken;  // your idToken
    pm.environment.set("FIREBASE_TOKEN", idToken ); // set environment variable FIREBASE_TOKEN with value idToken 
});

this code will add the environment variable FIREBASE_TOKEN, but u can do whatever you want with idToken =)

Upvotes: 10

sendon1982
sendon1982

Reputation: 11264

Here is the full list apis I found for interacting with Firebase by using its API endpoint directly.

https://www.any-api.com/googleapis_com/identitytoolkit/docs/relyingparty

enter image description here

Upvotes: 1

CybeX
CybeX

Reputation: 2406

For anyone still a bit confused, this works perfectly with Firebase using Auth emulators.

Brief Overview

  1. Create functions
  2. Setup emulator
  3. Generate Token
  4. Perform authed request(s)

1. Create functions

2 functions are required:

  1. Generate ID Token function:
import {https} from "firebase-functions";
import {auth} from "firebase-admin";

export const generateAuthToken = https.onCall((data, _context) => {
    if (!data.uid) {
        return new https.HttpsError("invalid-argument", "Missing UID argument", "Missing UID argument");
    }

    return auth().createCustomToken(data.uid).then(value => {
        console.log(`Token generated: ${value}`);
        return {
            status: true,
            token: value
        };
    }).catch(reason => {
        console.warn(reason);
        return {
            status: false,
            token: ""
        }
    });
});
  1. (optional) Auth'd function:
import {https} from "firebase-functions";
import {auth} from "firebase-admin";

export const checkAuthenticated = https.onCall((_data, context) => {
    if (!context.auth) {
        return new https.HttpsError("unauthenticated", "You need to be authenticated to retrieve this data");
    }

    return "Congratulations! It works.";

});

2. Setup environment

  • (optional) Setup emulators
  • Run your firebase project as you'd normally do
  • Postman, create 2 requests:

1. generateAuthToken

{
    "data": {
        "uid":"1234567890"
    }
}

2. checkAuthenticated

{
    "data": {

    }
}
  • Authentication Tab > Type Bearer: {insert token}

3. Generate Token

Call postman function using method described in 2.1

4. Perform authed request(s)

For every authed request, add the bearer token as described in 2.2 and it all works as expected.

Upvotes: 0

LordGift
LordGift

Reputation: 73

Firebase Auth not response Access Token just idToken. you must verify/exchange with your auth system to get it.

Upvotes: 1

IamToobDude
IamToobDude

Reputation: 60

If your using Node here's my solution,

With the firebase admin SDK import that into your file, and follow @naptoon instructions for setting up a route in PostMan.

In Nodejs in your file put the following const user = admin.auth().verifyIdToken(req.headers.authorization)

I tried using const auth = getAuth() const user = auth.currentUser

and that way didn't work for me so I went with the firebase admin route which worked well with minimal code

Upvotes: 0

Josh
Josh

Reputation: 309

Copy the below block of code and place it in the 'pre-request scripts' tab of the request on Postman. It will automatically get a token and put it as 'Authorization' header every time you make a request. You don't need to add any header or authorization manually. You don't even need to worry about token expiry.

Obviously, replace the app api key, username and password place holders.

const postRequest = {
  url: 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={APP_API_Key}',
  method: 'POST',
  header: {
    'Content-Type': 'application/json'
  },
  body: {
    mode: 'raw',
    raw: JSON.stringify({
    "email": "{Your_Email}",
    "password": "{Your_Password}",
    "returnSecureToken": true
})
  }
};

pm.sendRequest(postRequest, (error, response) => {
  var jsonData = response.json();
  pm.globals.set("id_token", jsonData.idToken)
});

pm.request.headers.add({key: 'Authorization', value: '{{id_token}}'})

Upvotes: 4

Andrew Mackrodt
Andrew Mackrodt

Reputation: 1826

I came across a need to do this where staging and production environments require a different Firebase idToken but local does not use one. I expanded upon naptoon's and leo's answers to use the identitytoolkit's verifyPassword endpoint as part of a pre-request:

const apiKey = pm.environment.get('api_key');

if ( ! apiKey) {
    return
}

const tokenEnv = pm.environment.get('token_env')

if (tokenEnv && tokenEnv === pm.environment.name) {
    const tokenTimestamp = Number.parseInt(pm.environment.get('token_timestamp'), 10)
    const elapsed = Date.now() - tokenTimestamp
    if (elapsed < 20 * 60000) {
        return
    }
}

pm.sendRequest({
    url: `https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=${apiKey}`,
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            email: pm.environment.get('auth_username'),
            password: pm.environment.get('auth_password'),
            returnSecureToken: true,
        }),
    },
}, function (err, res) {
    let json
    if ( ! err) {
        json = res.json()
        if (json.error) {
            err = json.error
        }
    }
    if (err) {
        pm.environment.unset('auth_token')
        pm.environment.unset('token_env')
        pm.environment.unset('token_timestamp')
        throw err
    }
    pm.expect(json.idToken).to.not.be.undefined
    pm.environment.set('auth_token', json.idToken)
    pm.environment.set('token_env', pm.environment.name)
    pm.environment.set('token_timestamp', Date.now())
})

The access token is cached for a given environment for up to 20 minutes (I have not implemented refresh token). The token is cleared if the environment is different to the last request or an error occurs.

Upvotes: 5

Volkov Maxim
Volkov Maxim

Reputation: 331

In addition of naptoon's post:

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id_token", jsonData.idToken);

This is "old style", which is deprecated by Postman. The "new style" is:

pm.environment.set("id_token", pm.response.json().idToken);

Upvotes: 6

Alberto L. Bonfiglio
Alberto L. Bonfiglio

Reputation: 1835

An easy way to retrieve the access token from firebase is to:

  1. create an html file in a directory
  2. copy in the html file the content of firebase auth quickstart
  3. replace the firebase-app.js and firebase-auth.js as explained in firebase web setup to point them at the proper cdn location on the web
  4. replace firebase.init script with the initialization code from your app on the console like this:
var config = {
    apiKey: "my secret api key",
    authDomain: "myapp.firebaseapp.com",
    databaseURL: "https://myapp.firebaseio.com",
    projectId: "myapp-bookworm",
    storageBucket: "myapp.appspot.com",
    messagingSenderId: "xxxxxxxxxxxxx"
};
firebase.initializeApp(config);
  1. open the html file in your browser and either sign in or sign up. The Firebase auth currentUser object value should be displayed.

    1. inspect the html and expand the quickstart-account-details element. This should have the json object displayed.

    2. copy the content of accessToken

    3. In postman go to authorization, select bearer token and paste the copied token in the token value field.

You should be now able to call apis that are secured by firebase auth. Keep in mind that this only gets and passes the access token so once the token is expired you may need to request a new one (steps 5 to 8)

you can also look at this
Hope this helps!

Upvotes: 12

naptoon
naptoon

Reputation: 1403

When you want to use Postman only and don't want to build a frontend you can use this auth request in Postman: POST https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={API_KEY}

In the Body you should send the following JSON string:

{"email":"{YOUR_EMAIL_ADDRESS}","password":"{PASSWORD}","returnSecureToken":true}

Content type is application/json (will be set automatically in Postman). You can find the Firebase API_KEY in the Firebase project settings (it's the Web-API-key).

As response you will get a JSON object and the idToken is the token you need for all your API requests as Bearer token.

To have a automated setting of this token, you can add the following code in the Tests tab at your auth request:

var jsonData = JSON.parse(responseBody);
postman.setGlobalVariable("id_token", jsonData.idToken);

For all your API requests you should set the Authorization to Bearer Token and the value for the token is {{id_token}}.

Now the token will be automatically used once you executed the auth request and got the response.

Upvotes: 123

Related Questions