Get Firebase Access Token in POSTMAN

19,041

Solution 1

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!

Solution 2

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.

Solution 3

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 =)

Solution 4

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.

Solution 5

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);
Share:
19,041

Related videos on Youtube

Farhan Chauhan
Author by

Farhan Chauhan

I am a Software Engineer, And mainly interested in Html, Css, AngularJs, Jquery, Js.

Updated on April 02, 2022

Comments

  • Farhan Chauhan
    Farhan Chauhan over 2 years

    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)

    • DauleDK
      DauleDK about 6 years
      I dont understand this question. Why do you need the access token from firebase, if your goal is to access any API? Do you mean any firebase API? And also, in your web app how do you use the authentication. Do you use the SDK or the firebase REST api?
    • Farhan Chauhan
      Farhan Chauhan about 6 years
      @DauleDK I am using firebase SDK. Firebase Access Token is required to generate Cookie from server side. API will return response only if valid cookie present in request.
  • jean d'arme
    jean d'arme over 4 years
    What when token expires?
  • MikeG
    MikeG about 4 years
    I'm able to get the expected response back by POST to the endpoint you've suggested, but when I try to verify the ID Token via firebase admin sdk in my Node app I get Error: Decoding Firebase ID token failed. Make sure you passed the entire string JWT which represents an ID token . Any suggestions?
  • MikeG
    MikeG about 4 years
    Oops, Postman was adding "Bearer" to the beginning of the token string when i set the auth type to "Bearer Token"
  • A-S
    A-S about 4 years
    If you're getting the following error, just change the type of authorization (under the Authorization tab in Postman's request) to OAuth 2.0. No need to provide any further details. The error I got before doing so:
  • A-S
    A-S about 4 years
    { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsol‌​e-project.", "errors": [ { "message": "Invalid Credentials", "domain": "global", "reason": "authError", "location": "Authorization", "locationType": "header" } ], "status": "UNAUTHENTICATED" } }
  • tyirvine
    tyirvine almost 4 years
    I'd like to add that in the "email":"{YOUR_EMAIL_ADDRESS}","password":"{PASSWORD}" fields, use a user account, not the Firebase sign-in account lol. Silly mistake
  • David Ritchie
    David Ritchie over 3 years
    Has anyone managed to get this working with the Authentication Emulator?
  • Shubham A.
    Shubham A. about 3 years
    What should be the request body if I have opted for the phone sign-in method, using the phone number and an OTP? I have added the test phone number and the OTP in the Firebase console but what is the request body attributes?
  • Samuel
    Samuel over 2 years
    I've gained the idToken successfully, but I get "401 Unauthorized" & "Your client does not have permission to the requested URL" when I access the API with my bearer token set.
  • Jobin S
    Jobin S over 2 years
    @ShubhamA. do you got the solution
  • Shubham A.
    Shubham A. over 2 years
    Yes, I did got the solution.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
  • sendon1982
    sendon1982 over 2 years
    @jeand'arme Token expired at 3600 seconds. response has a field: ` "expiresIn": "3600" `