Skip to content

Instantly share code, notes, and snippets.

@droduit
Last active January 6, 2023 01:24
Show Gist options
  • Save droduit/023dd7e90543950ff96f10f916c0f465 to your computer and use it in GitHub Desktop.
Save droduit/023dd7e90543950ff96f10f916c0f465 to your computer and use it in GitHub Desktop.
Add Authorization header with firebase user token to every request made with axios across the application
/*
* Backend implementation: express middleware which checks the firebase user token and execute the request only when the token is verified
*/
import * as express from "express";
import * as admin from "firebase-admin";
import * as functions from "firebase-functions";
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
const app = express();
app.use('/', (req, res, next) => {
const headerToken = req.header('Authorization');
if (!headerToken) {
res.status(401).send({message: 'Auth token must be provided'});
return;
}
const headerParts = headerToken.split(" ");
if (headerParts.length < 2 || headerParts[0] !== 'Bearer' || !headerParts[1]) {
res.status(401).send({message: 'Invalid token'});
return;
}
admin
.auth()
.verifyIdToken(headerParts[1])
.then((decodedToken) => {
next();
})
.catch((error) => {
res.status(403).send({message: error.message}).end();
});
});
app.get("/", async (req, res) => {
res.status(200).send('Request executed successfully').end();
});
export const users = functions.region("europe-west6").https.onRequest(app);
/*
* How to use the fetchClient in the frontend
*/
import fetchClient from "./fetchClient";
fetchClient.get('https://url.api.com/users').then(res => {
console.log(res);
});
fetchClient.patch('https://url.api.com/users/{uid}', payload).then(res => {
// ...
});
/*
* Frontend implementation of a custom axios instance
*/
import axios from 'axios';
import firebase from 'firebase/app';
import "firebase/auth";
const fetchClient = (() => {
const getAuthToken = async () => {
try {
return "Bearer " + await firebase.auth().currentUser?.getIdToken();
} catch(err) {
console.log("getAuthToken", err);
};
};
const instance = axios.create({
baseURL: 'https://url.api.com'
});
instance.interceptors.request.use(async (config) => {
config.headers.Authorization = await getAuthToken();
return config;
});
return instance;
})();
export default fetchClient;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment