How to use my firebase authentication to work with external services? - firebase

Ok so I am using firebase as authentication for my iOS app. Now I plan on adding video calling to my app using an external service know as connectyCube. This service has their own authentication system and I cannot use their services unless a user is authenticated.
Option 1: I can use their own authentication which means my app would have two authentication systems - not very productive
Option 2: They say I can use an existing authentication to validate users
I understand that this is a common thing in the developers world and I see the word OAuth and JWT being thrown around but I am a rookie developer and I want to understand how I can use firebase and authenticate a user from an external service.
These are the questions they have asked when I opted for the "I have my own authentication" option:
What is your end point URL
Is it GET or POST
Request Headers
Request Params
Response Params
Where do I get all this information from firebase? Any help would be great

As an alternative to #Dharmaraj's answer, you could instead make use of a HTTP Event Cloud Function for this based on the code sample they've provided.
Using this method, you create the endpoint /verifyUserToken to be used by ConnectyCube.
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
export const verifyUserToken = functions.https.onRequest((req, res) => {
const idToken = req.query.token;
verifyUser(idToken)
.then(
(userData) => {
res.status(200).json(userData)
},
(err) => {
console.log("Token verification failed.", err.code || err.message);
res.status(422).json({error: "User token is invalid"})
}
)
.catch((err) => console.error("Unexpected crash", err));
});
async function verifyUser(token) {
if (!token)
throw new Error("token missing");
// using `true` here to force token to be checked against the Firebase
// Auth API rather than trusting its contents as-is
const { uid, email } = await admin.auth().verifyIdToken(token, true);
// pull the user's username from their user data
// at /users/{userId}/username
const username = (await admin.database().ref("users/" + uid + "/username")).val();
// use user's actual email if available, otherwise fallback
// to a userID based email
const uEmail = email || uid + "#users.noreply.yourapp.com";
// use user's username if available, otherwise fallback to
// the email address above.
const uLogin = username !== null ? username : uEmail;
return {
uid,
login: uLogin,
email: uEmail,
user: {id: uid, login: uLogin, email: uEmail}, // <- this part in particular is used by ConnectyCube
users: [{uid, login: uLogin, email: uEmail}]
};
}
Once deployed, you would use the following settings:
Setting
Value
API URL:
https://us-central1-PROJECT-ID.cloudfunctions.net/verifyUserToken
GET/POST
GET
Request params:
{"token": "#{login}"}
Response params:
{"uid": "#{user.id}", "email": #{user.email}, "login": "#{user.login}"}

It looks like ConnectyCube uses some sort of Session Tokens as mentioned in their documentation with their own username and password.
The most easiest way would be creating a ConnectyCube account whenever a new user signs up in your Firebase app using Firebase Auth Triggers for Cloud functions. Then you can generate username and password on behalf of your user and store them in a Database.
So whenever you need to create a ConnectyCube session, check for the currently logged in user and fetch their ConnectyCube credentials.
async function createCCSession() {
const userId = firebase.auth().currentUser.uid
const ccCrednetials = (await firebase.database().ref(`ccCreds/${userId}`).once('value')).val()
ConnectyCube.createSession(ccCredentials)
.then((session) => {
console.log(session)
return session
}).catch((error) => console.log(error));
}
You can protect the database using security rules so a user can access their credentials only.
{
"rules": {
"ccCreds": {
"$uid": {
".read": "$uid === auth.uid"
}
}
}
}

While I don't normally double-answer a question, in the course of exploring some other authentication related problems, I've managed to eliminate the Cloud Function from my other answer entirely and instead call the Authentication API directly.
Setting
Value
API URL:
https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key=FIREBASE_CONFIG_API_KEY
GET/POST
POST
Request params:
{"idToken": "#{login}"}
Response params:
{"uid": "#{users.0.localId}", "email": #{users.0.email}, "full_name": "#{users.0.displayName}"}
On your client, you just call the ConnectyCube Login API with the following data:
POST https://api.connectycube.com/login
login=<Firebase-ID-token>
password=<any-random-value-to-pass-the-validation>

Related

Can I get a Google user identify from their access_token?

Implementing Google OAuth in Firebase Cloud Functions.
Everything is working but I have a weird issue. Everything is working, but I don't know how to identify the user to save the tokens to their user object in Firestore.
Using the google API nodejs library, I create an authURL using the OAuth2 client, set the scopes etc, then redirect the user to it. This works great.
const {google} = require('googleapis');
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);
const scopes = [
'https://www.googleapis.com/auth/calendar'
];
const authorizationUrl = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
state: 'state_parameter_gets_passed_back',
scope: scopes,
// Enable incremental authorization. Recommended as a best practice.
include_granted_scopes: true
});
console.log('created an authorizationUrl: ' + authorizationUrl);
res.redirect(authorizationUrl);
I then have an https Cloud Function endpoint set as the redirect URL, waiting for the response.
When it comes I get the code and request the tokens. This also works great, until I get to saveUserToken. Who is the user? My Cloud Function is just listening to responses
exports.recieveGoogleCodeFromResponseURL = functions.https.onRequest(async (req, res) => {
const code = req.query.code;
console.log('got a code, it is:' + code);
const url = require('url');
if (req.query.code != null) {
let userCredential;
console.log('we have a code, trading it for tokens');
let { tokens } = await oauth2Client.getToken(code);
console.log({ tokens });
oauth2Client.setCredentials(tokens);
//THIS IS THE PROBLEM HERE, who is the user to save the tokens to?
saveUserToken(tokens, uid); //saves to Firestore
}
res.json({result: `Got a response from Google`, code: code, scope: req.query.scope});
});
The response looks like this:
{
access_token: "longtoken",
expiry_date: 166...,
refresh_token: "anothertoken",
scope: "https://www.googleapis.com/auth/calendar",
token_type: "Bearer"
}
From what I understand neither the access_token or refresh_token is JWT token I could decode to get user info.
All of the Firebase Cloud Functions examples I have read from Google say something like 'In production you would save this token to a secure persistent DB', which I can do with Firestore. I just can't figure out how to ID the user the callback and code belongs to.
All the code samples that show OAuth with other services (Instagram, LinkedIn, Twitch) either the results come with the user id, or their API allows you to query the service with just the access_token and get the user.
For example in this Login with Instagram example the response comes with the user Id.
Code here > https://github.com/firebase/functions-samples/blob/main/instagram-auth/functions/index.js
const oauth2 = instagramOAuth2Client();
const results = await oauth2.authorizationCode.getToken({
code: req.query.code,
redirect_uri: OAUTH_REDIRECT_URI,
});
functions.logger.log('Auth code exchange result received:', results);
// We have an Instagram access token and the user identity now.
const accessToken = results.access_token;
const instagramUserID = results.user.id;
In this OAuth example from LinkedIn, once again they pass the access token to a LinkedIn endpoint to identify the user. Code here https://github.com/firebase/functions-samples/blob/main/linkedin-auth/functions/index.js
const linkedin = Linkedin.init(results.access_token);
linkedin.people.me(async (error, userResults) => {
if (error) {
throw error;
}
functions.logger.log(
'Auth code exchange result received:',
userResults
);
// We have a LinkedIn access token and the user identity now.
const linkedInUserID = userResults.id;
I can use this Google library to validate an ID token, but I am not getting an ID token back from the OAuth process.
Feels like I am missing something simple. Is there a Google API I can pass an access_token to to identify the user?
The access_token returned by Google OAuth is not a JWT. It's an opaque string that is only meaningful to Google, and that you can use to identify the user with Google APIs.
You can use the Google People API to get information about the user. With the access_token you can query the Google People API and get information about the user
Sh_ghosa's answer sent me down a misleading rabbit hole so I'm providing this answer to protect your time that I've spent for you.
The following code example uses the NodeJS Google Cloud SDK and therefore assumes that the GoogleAuth module is provided in the language you're using.
// libraries (npm)
const {google} = require('googleapis');
const jwt = require('jsonwebtoken');
// business logic
const auth = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const authClient = await auth.getClient();
const accessToken = await authClient.getAccessToken();
const decodedJwt = jwt.decode(accessToken?.res?.data?.id_token);
const principal = decodedJwt?.email; // <:: the principal
console.log('Who am I? ', principal);
Found a solution.
Ask for additional scopes
At first I was just asking for Google Calendar permissions.
const scopes = 'https://www.googleapis.com/auth/calendar'
The trick is to ask for email, and profile as well,
const scopes = 'https://www.googleapis.com/auth/calendar email profile'
If you ask for these additional scopes, Google sends back an id_token with the access_token and the refresh_token
You can get the user email and other information from that id_token.
You can decode the token locally since it came from a secure https session with Google and you check that the state variable passed back matches the one your system generated.
function decodeIdTokenLocally(token){
//we split the id_token at the period ., and just decode the 2nd part
let secondPart = token.split('.')[1];
let localUserJsonString = atob(secondPart);
let localUser = JSON.parse(localUserJsonString);
return localUser
}
Quick note - Asking for more than 1 scope at once gives this ugly checkbox interface where users have to manually click the checkboxes of the scope you are asking for.
Better to have them Login With Google first, which grants the email and profile scopes, then ask for Calendar scope or additional scopes one at a time which will present the nice one click to accept interface.
I haven't tried #sh_gosha suggestion of sending the access_token to the Google People API but I think that would work as well, but it would add an additional API call.

Migrating salted sha512 passwords from symfony 2 to firebase authentication

I am trying to migrate users (including passwords) from an old symfony 2 application to firebase authentication (or google identity platform).
In the symfony2 application the passwords of the users are hashed using sha512 with a salt. I already found that users can be imported using their password and hash in the documentation of firebase (https://firebase.google.com/docs/auth/admin/import-users). However it seems like the sha512 hashing that is used by firebase is not the same as was used by symfony.
For the old symfony project the following configuration is used:
security:
encoders:
FOS\UserBundle\Model\UserInterface: sha512
By looking into the source I found that symfony given a salt and a password symfony will produce the hash like this: (in python code)
def get_hash(salt, password):
hash = password.encode('utf-8')
salted = hash + salt
hash = hashlib.sha512(salted).digest()
for i in range(1, 5000):
# symfony keeps adding salted for every iteration, this is something firebase does not it seems
hash = hashlib.sha512(hash + salted).digest()
return base64.b64encode(hash).decode('utf-8')
However this code does not allow me to login when i import it like in the code below. It however does produce the same hash as I have in my database of the symfony2 application:
app = firebase_admin.initialize_app()
salt = '{test}'.encode('utf-8')
hash = get_hash(salt=salt, password='xyz')
print('calculated hash', base64.b64encode(hash))
users = [
auth.ImportUserRecord(
uid='foobar',
email='foo#bar.com',
password_hash=hash,
password_salt=salt
)
]
hash_alg = auth.UserImportHash.sha512(rounds=5000)
try:
result = auth.import_users(users, hash_alg=hash_alg)
for err in result.errors:
print('Failed to import user:', err.reason)
except exceptions.FirebaseError as error:
print('Error importing users:', error)
I can however login with the password when i use the following fuction.
def get_hash(salt, password):
hash = password.encode('utf-8')
salted = salt + hash
hash = hashlib.sha512(salted).digest()
for i in range(1, 5000):
hash = hashlib.sha512(hash).digest()
return hash
I have already found a way to change the order of adding the salt but i can find no way to hash like this in firebase hash = hashlib.sha512(hash + salted).digest().
Now it seems like there is no way to migrate my password to firebase as the implementation of symfony is a bit different from the one used by firebase. Does anyone know a way to make sure I can still import my current hashes? This would be great.
If not, what would be alternative work arounds?
Is it possible to let firebase do a request to my own endpoint to verify password.
Another way would be to try to catch the signin process and send it to my own endpoint first, set the password in the background and then send the request to firebase?
You haven't specified what your client application is using, so I'm just going to assume it's a web application that will use the Firebase Web SDK.
To use this solution, you'll need to migrate the Symfony user data to Firestore under a private _migratedSymfonyUsers collection, where each document is the email of that user.
On the client, the process will be:
Collect email and password from the user
Attempt to sign in to Firebase with that email and password combination
If that failed, invoke a Callable Cloud Function with that email and password combination.
If function returned a success message (see below), reattempt signing in the user with the given email and password
Handle success/errors as appropriate
On the client, this would look like:
const legacySignIn = firebase.functions().httpsCallable('legacySignIn');
async function doSignIn(email, password) {
try {
return await firebase.auth()
.signInWithEmailAndPassword(email, password);
} catch (fbError) {
if (fbError.code !== "auth/user-not-found")
return Promise.reject(fbError);
}
// if here, attempt legacy sign in
const response = await legacySignIn({ email, password });
// if here, migrated successfully
return firebase.auth()
.signInWithEmailAndPassword(email, password);
}
// usage:
doSignIn(email, password)
.then(() => console.log('successfully logged in/migrated'))
.catch((err) => console.error('failed to log in', err));
In the Callable Cloud Function:
(optional) Assert that the request is coming from your application with App Check
Assert email and password were provided and throw error if not.
Assert that the email given exists in your migrated users and throw an error if not.
If in migrated users, hash the password and compare against the stored hash.
Throw an error if hashes don't match.
If hashes match, create a new Firebase user with that email and password combination
Once created, delete the migrated hash and return success message to the caller
On the server, this would look like:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
function symfonyHash(pwd, salt) {
// TODO: Hash function
return /* calculatedHash */;
}
exports.legacySignIn = functions.https.onCall(async (data, context) => {
if (context.app == undefined) { // OPTIONAL
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.');
}
if (!data.email || !data.password) {
throw new functions.https.HttpsError(
'invalid-argument',
'An email-password combination is required');
}
if (data.email.indexOf("/") > -1) {
throw new functions.https.HttpsError(
'invalid-argument',
'Email contains forbidden character "/"');
}
const migratedUserSnapshot = await admin.firestore()
.doc(`_migratedSymfonyUsers/${data.email}`);
if (!migratedUserSnapshot.exists) {
throw new functions.https.HttpsError(
'not-found',
'No user matching that email address was found');
}
const storedHash = migratedUserSnapshot.get("hash");
const calculatedHash = symfonyHash(password, salt);
if (storedHash !== calculatedHash) {
throw new functions.https.HttpsError(
'permission-denied',
'Given credential combination doesn\'t match');
}
// if here, stored and calculated hashes match, migrate user
// get migrated user data
const { displayName, roles } = migratedUserSnapshot.data();
// create the user based on migrated data
const newUser = await admin.auth().createUser({
email,
password,
...(displayName ? { displayName } : {})
});
if (roles) { // <- OPTIONAL
const roleMap = {
"symfonyRole": "tokenRole",
"USERS_ADMIN": "isAdmin",
// ...
}
const newUserRoles = [];
roles.forEach(symfonyRole => {
if (roleMap[symfonyRole]) {
newUserRoles.push(roleMap[symfonyRole]);
}
});
if (newUserRoles.length > 0) {
// migrate roles to user's token
await setCustomUserClaims(
newUser.uid,
newUserRoles.reduce((acc, r) => { ...acc, [r]: true }, {})
);
}
}
// remove the old user data now that we're done with it.
await hashSnapshot.ref.delete();
// return success to client
return { success: true };
});

How to access classroom api after signing through Firebase using Google Sign-in

I have created a unity application to sign-in using google and access google-classroom api. The sign-in is successful and the scope allows access to the courses too.
Question:
How to query the google classroom api after signing in with firebase.
endpoint : https://classroom.googleapis.com/v1/courses/105459102203
Method : GET
Parameter : CourseId which I already have
BearerToken : How to retrieve this from firebase?
When I try using auth-code and/or idToken it gives the following error:
{
"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/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}
Thanks in advance.
There are many ways to make a succesfully API request via firebase Auth, in particulary to Google Classroom API:
The hard way is to create a HttpInterceptor for the firebase.UserCredentials and pass it on headers of every HttpRequest, somethis like this:
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
Authorization: `Bearer [${this.user$.AccessToken}]`
})
this is what I call the hard way because you have to ensure to pass and refresh tokens y every API services.
Use the javascript library "gapi" to login the client, and then use the token response as credential to login in Firebase. This aproach creates a pure OAuth2 login that serves to Firebase and further Google APIs requests, as follows:
declare var gapi;
/** Initialize Google API Client */
initClient(): void {
gapi.client.init({
apiKey: environment.firebaseConfig.apiKey,
clientId: environment.firebaseConfig.clientId,
discoveryDocs: environment.firebaseConfig.discoveryDocs,
scope: environment.firebaseConfig.scope,
});
}
/** Do a OAuth login and then pass it to a FirebaseAuth service */
async login() {
const googleAuth = gapi.auth2.getAuthInstance();
const googleUser = await googleAuth.signIn();
const token = googleUser.getAuthResponse().id_token;
const credential = firebase.auth.GoogleAuthProvider.credential(token);
await this.afAuth().signInAndRetrieveDataWithCredential(credential);
}
/** Then you're ready to make a request*/
/**
* Lists all course names and ids.
* Print the names of the first 10 courses the user has access to. If
* no courses are found an appropriate message is printed.
*/
listCourses() {
this.courses$ =
gapi.client.classroom.courses.list({pageSize=10;}).then(response => {
return from<Course[]>(response.result.courses);
});
}

firebase auth with MIcrosoft Graph (accessToken)

I am super hopeful someone can help me - I'm kind of stuck.
I'm happily using firebase auth with Microsoft AD. My AuthProvider is firebase.auth.OAuthProvider('microsoft.com').
When I call firebase.auth().signInWithPopup() with that provider, everything works GREAT. I can pick out the accessToken from the resulting UserCredential and access Microsoft Graph api's no problem (yay!).
Firebase persists and renews the authentication and my app gets the expected callback via onAuthStateChanged with the new firebase.User when the user returns to my SPA later (also yay!).
The bad news (where I'm stuck) is: how do I get the Microsoft Graph accessToken in this flow (e.g. when the user returns to my app later)? I don't want them to have to re-authenticate with another popup (yech).
Basically, how do I go from a valid firebase.User to a MS Graph accessToken when the user returns?
Thanks so so much for any help!
Firebase Auth only focuses on authentication only. They will return the OAuth access token on sign in success via UserCredential but will discard the Microsoft OAuth refresh token and not store any OAuth credential associated with the provider. So you have no way to get a new access token afterwards. If you have a good reason for Firebase Auth to manage OAuth access tokens, please file an official feature request.
UPDATE/answer: so it turns out to be simpler than I thought:
The basic idea is to authenticate (re-authenticate) using firebase and use the same clientID for silent microsoft authentication. However, you must supply a loginHint
parameter to the microsoft auth, even if you were previously authorized. loginHint can
be the email address for the firebase user...
In that scenario, the authentication is shared and you won't need to popup a second sign-in for the "microsoft half" of the process - the firebase auth works fine.
I ended up using microsoft's MSAL library (https://github.com/AzureAD/microsoft-authentication-library-for-js)... something like this:
const graphDebug = false;
const msalLogger = new Logger(msalLogCallback, { level: LogLevel.Error });
export async function graphClient(loginHint: string) {
const msal = new UserAgentApplication({
// gotcha: MUST set the redirectUri, otherwise get weird errors when msal
// tries to refresh an expired token.
auth: { clientId: CLIENT_ID, redirectUri: window.location.origin },
system: { logger: msalLogger },
// TODO: should we set cache location to session/cookie?
});
/**
* Create an authprovider for use in subsequent graph calls. Note that we use
* the `aquireTokenSilent` mechanism which works because firebase has already
* authenticated this user once, so we can share the single sign-on.
*
* In order for that to work, we must pass a `loginHint` with the user's
* email. Failure to do that is fatal.
*/
const authProvider: AuthProvider = callback => {
msal
.acquireTokenSilent({ scopes: SCOPES, loginHint })
.then(result => {
callback(null, result.accessToken);
})
.catch(err => callback(err, null));
};
const client = Client.init({
authProvider,
debugLogging: graphDebug,
});
return client;
}
When you are using signInWithPopup, the result object contains the credentials you are looking for.
firebase.auth().signInWithPopup(provider)
.then(function(result) {
// User is signed in.
// IdP data available in result.additionalUserInfo.profile.
// OAuth access token can also be retrieved:
// result.credential.accessToken
// OAuth ID token can also be retrieved:
// result.credential.idToken
})
.catch(function(error) {
// Handle error.
});
Hope this helps.
If you look deep enough you should find msal access token in firebase response under (firebaseAuth.currentUser as zzx).zzj()

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)
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.
An easy way to retrieve the access token from firebase is to:
create an html file in a directory
copy in the html file the content of firebase auth quickstart
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
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);
open the html file in your browser and either sign in or sign up. The Firebase auth currentUser object value should be displayed.
inspect the html and expand the quickstart-account-details element. This should have the json object displayed.
copy the content of accessToken
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!
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);
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 =)
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.
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}}'})
Firebase Auth not response Access Token just idToken. you must verify/exchange with your auth system to get it.
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
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
For anyone still a bit confused, this works perfectly with Firebase using Auth emulators.
Brief Overview
Create functions
Setup emulator
Generate Token
Perform authed request(s)
1. Create functions
2 functions are required:
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: ""
}
});
});
(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
Method: POST
URL: http://127.0.0.1:5001/{project-name}/{region}/generateAuthToken
Headers:
"Content-Type": "application/json; charset=utf-8"
body (RAW: JSON)
{
"data": {
"uid":"1234567890"
}
}
2. checkAuthenticated
Method: POST
URL: http://127.0.0.1:5001/{project-name}/{region}/checkAuthenticated
Headers:
"Content-Type": "application/json; charset=utf-8"
body (RAW: JSON)
{
"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.

Resources