Keeping authentication state between Firebase - WebApp (.NET Core MVC) - firebase

I am creating an ASP.NET Core MVC app, where the authentication provider will be FireBase.
My Web App is hosted in Azure and, once user signs in, it sends an HTTPS request to my firebase endpoint, which looks like https://myFirebaseApp.cloudfunctions.net/signup with username and password, and it will create a user as below;
https://firebase.google.com/docs/auth/web/start?authuser=0
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
My intention is to get a kind of session token in the response and save it in a cookie. And everytime user navigates to another page, I will need to validate that cookie/token to keep authentication persistent.
What would be the way to achieve this? Or is there any better practice to keep this integration?

I found out I can use custom tokens for this. What I need to use is createCustomToken and
signInWithCustomToken methods.
https://firebase.google.com/docs/auth/admin/create-custom-tokens
Create Token:
createCustomToken(request, response) {
let uid = request.query.uid;
if (!uid) {
response.send("query.uid is required.");
return;
}
let additionalClaims = {
myExtraField: 1
};
this.admin
.auth()
.createCustomToken(uid, additionalClaims)
.then(function(customToken) {
// Send token back to client
response.send(customToken);
})
.catch(function(error) {
response.send(error);
});
}
Sign-in:
signInWithCustomToken(request, response) {
const id_token = request.query.id_token;
if (!id_token) {
response.send("query.id_token is required.");
return;
}
// Sign in with signInWithCustomToken.
this.authService
.signInWithCustomToken(id_token)
.then(result => {
response.send(result);
})
.catch(error => {
response.send(error);
});
}

Related

What is the best way to send firebase user token from frontend to backend in API Auth header without having to fetch token each time ? (NextJs))

I need to send firebase user token in API authorization header in each API request in my next.js app.
Current Implementation:
axios.interceptors.request.use(
async (config) => {
const token = await firebase.auth().currentUser?.getIdToken(true);
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
)
But the issue with this implementation is to User Token from firebase is fetched before each request which is effecting the performance of the applications.
Is there a better way to implement it ? I am thinking to store the token in local storage and get token from localStorage instead of firebase.
firebase.auth().onAuthStateChanged(async (user) => {
try {
if (user) {
const token = await user.getIdToken(true);
await localStorage.setItem("app_session", token);
}
} catch (err) =>{
// Handle error
}
}
And use it like this
axios.interceptors.request.use(
async (config) => {
const token = localStorage.getItem("app_session");
if (token) {
config.headers["Authorization"] = "Bearer " + token;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
There is a lot written on the subject of how best to store authentication tokens in frontend applications. There are several solutions and each has its pros and cons. This previous answer might give you some ideas.
This article gives a nice overview and explains why storing in memory might be the best option. Here is another article with a similar conclusion
In your case, you might store the token in memory. When required, check for its existence, and if it is not in memory (think browser refresh) make the call to Firebase to retrieve the token and store it in memory again.
Of course, you should look at your specific context and needs and decide if any of the other solutions, such as localStorage, might work for you and your security requirements.

Integrate custom Oauth provider with firebase.auth().signInWithRedirect?

I setup a Twitch OAuth integration using the Instagram example, now I can login into my app by opening the popup.html page that the example gave me.
Here's my adapted code:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const { AuthorizationCode } = require('simple-oauth2');
const fetch = require('node-fetch');
// Firebase Setup
const admin = require('firebase-admin');
// #ts-ignore
const serviceAccount = require('./service-account.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: `https://${process.env.GCLOUD_PROJECT}.firebaseio.com`,
});
const OAUTH_REDIRECT_URI = `https://${process.env.GCLOUD_PROJECT}.firebaseapp.com/popup.html`;;
const OAUTH_SCOPES = 'user:read:email';
/**
* Creates a configured simple-oauth2 client for Twitch.
*/
function twitchOAuth2Client() {
// Twitch OAuth 2 setup
// TODO: Configure the `twitch.client_id` and `twitch.client_secret` Google Cloud environment variables.
const credentials = {
client: {
id: functions.config().twitch.client_id,
secret: functions.config().twitch.client_secret,
},
auth: {
tokenHost: 'https://id.twitch.tv',
tokenPath: '/oauth2/token',
authorizePath: '/oauth2/authorize',
},
options: {
bodyFormat: 'json',
authorizationMethod: 'body',
},
};
return new AuthorizationCode(credentials);
}
/**
* Redirects the User to the Twitch authentication consent screen. Also the 'state' cookie is set for later state
* verification.
*/
exports.redirect = functions.https.onRequest((req, res) => {
const authorizationCode = twitchOAuth2Client();
cookieParser()(req, res, () => {
const state = req.cookies.__session || crypto.randomBytes(20).toString('hex');
console.log('Setting verification state:', state);
res.cookie('__session', state.toString(), { maxAge: 3600000, httpOnly: true });
const redirectUri = authorizationCode.authorizeURL({
redirect_uri: OAUTH_REDIRECT_URI,
scope: OAUTH_SCOPES,
state: state,
});
console.log('Redirecting to:', redirectUri);
res.redirect(redirectUri);
});
});
/**
* Exchanges a given Twitch auth code passed in the 'code' URL query parameter for a Firebase auth token.
* The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie.
* The Firebase custom auth token, display name, photo URL and Twitch acces token are sent back in a JSONP callback
* function with function name defined by the 'callback' query parameter.
*/
exports.token = functions.https.onRequest((req, res) => {
const authorizationCode = twitchOAuth2Client();
try {
cookieParser()(req, res, async () => {
try {
console.log('Received verification state:', req.cookies.__session);
console.log('Received state:', req.query.state);
if (!req.cookies.__session) {
throw new Error(
'State cookie not set or expired. Maybe you took too long to authorize. Please try again.'
);
} else if (req.cookies.__session !== req.query.state) {
throw new Error('State validation failed');
}
} catch (error) {
return res.jsonp({ error: error.toString() });
}
let accessToken;
try {
console.log('Received auth code:', req.query.code);
const options = {
client_id: functions.config().twitch.client_id,
client_secret: functions.config().twitch.client_secret,
code: req.query.code,
grant_type: 'authorization_code',
redirect_uri: OAUTH_REDIRECT_URI,
};
console.log('Asking token with options', JSON.stringify(options));
accessToken = await authorizationCode.getToken(options);
console.log('Auth code exchange result received');
const twitchUser = await getTwitchUser(accessToken.toJSON().access_token);
// Create a Firebase account and get the Custom Auth Token.
const firebaseToken = await createFirebaseAccount(twitchUser);
// Serve an HTML page that signs the user in and updates the user profile.
return res.jsonp({ token: firebaseToken });
} catch (error) {
return res.jsonp({ error: error.toString() });
}
});
} catch (error) {
return res.jsonp({ error: error.toString() });
}
});
/**
* Creates a Firebase account with the given user profile and returns a custom auth token allowing
* signing-in this account.
*
* #returns {Promise<string>} The Firebase custom auth token in a promise.
*/
async function createFirebaseAccount(twitchUser) {
// The UID we'll assign to the user.
const uid = `twitch:${twitchUser.id}`;
// Save the access token to the Firebase Database.
const db = admin.firestore();
const databaseTask = db.collection('users').doc(uid).set(twitchUser);
// Create or update the user account.
const userCreationTask = admin
.auth()
.updateUser(uid, {
displayName: twitchUser['display_name'],
photoURL: twitchUser['profile_image_url'],
email: twitchUser['email'],
})
.catch((error) => {
// If user does not exists we create it.
if (error.code === 'auth/user-not-found') {
return admin.auth().createUser({
uid: uid,
displayName: twitchUser['display_name'],
photoURL: twitchUser['profile_image_url'],
email: twitchUser['email'],
});
}
throw error;
});
// Wait for all async task to complete then generate and return a custom auth token.
await Promise.all([userCreationTask, databaseTask]);
// Create a Firebase custom auth token.
const token = await admin.auth().createCustomToken(uid);
console.log('Created Custom token for UID "', uid, '" Token:', token);
return token;
}
async function getTwitchUser(accessToken) {
console.log('Fetching Twitch user with access_token', accessToken);
try {
const response = await fetch('https://api.twitch.tv/helix/users', {
method: 'GET',
headers: {
'Client-Id': functions.config().twitch.client_id,
Authorization: 'Bearer ' + accessToken,
},
});
const data = await response.json();
return { ...data.data[0], access_token: accessToken };
} catch (error) {
console.error(error);
}
}
I'd like, though, to login into Twitch using the firebase.auth().signInWithRedirect() method that I already use for Facebook and Google, unfortunately I can't find any documentation about this, and the Facebook provider source code refers to some externs.* resources so I'm not sure how to adapt it for my own needs.
Right now I have two endpoints/cloud functions: _twitchRedirect and _twitchToken, what should I do to integrate them with signInWithRedirect?
I was similarly curious, so spent a little time playing around with things today.
In short, when using Firebase Auth, I believe the providerId will need to be one of the existing supported providers.
If you upgrade to using the Google Cloud Identity Platform though, I believe you will be able to configure custom providers, and then use this function to authenticate:
https://cloud.google.com/identity-platform
We can see that firebase.auth.OAuthProvider and firebase.auth().signInWithPopup (or firebase.auth().signInWithRedirect) are used with a number of the providers here, eg.
https://cloud.google.com/identity-platform/docs/web/apple
https://cloud.google.com/identity-platform/docs/web/microsoft
In addition to these provider choices that we get with the standard Firebase Auth, Google Cloud Identity Platform allows us to also add SAML and OpenID Connect (OIDC) integrations:
https://cloud.google.com/identity-platform/docs/web/saml
https://cloud.google.com/identity-platform/docs/web/oidc
When adding a new identity provider using either of these, we are able to specify the 'Provider ID' to use (prefixed with either saml. or oidc.). This custom provider ID is then used with firebase.auth.OAuthProvider and firebase.auth().signInWithPopup (or firebase.auth().signInWithRedirect) as described above.
For example, if I created a new identity provider with an ID of oidc.foo, my integration code would end up looking like:
const provider = new firebase.auth.OAuthProvider('oidc.foo');
firebase.auth().signInWithPopup(provider)
.then((result) => {
// result.credential is a firebase.auth.OAuthCredential object.
// result.credential.providerId is equal to 'oidc.foo'.
// result.credential.idToken is the OIDC provider's ID token.
})
.catch((error) => {
// Handle error.
});
Based on my understanding of this, I believe we will only currently be able to add custom providers this way if they conform to the OpenID Connect (OIDC) standard (including the OIDC Discovery part, which uses a /.well-known/openid-configuration URL):
Note: If your OIDC provider doesn't comply with the OIDC specification for discovery, it won't work with Identity Platform.
So to my knowledge, the best way to implement 'normal' OAuth2 providers currently is the custom backend function flow you used above (based on the Firebase Auth examples).
As part of figuring this out, I decided to see what would happen if I used a provider ID that didn't match anything configured in my account (this is a fairly verbose step by step, and the main answer is already included above, but this may help provide some more context/help someone out, so including it here)
var provider = new firebase.auth.OAuthProvider("foo.example.com");
firebase
.auth()
.signInWithRedirect(provider)
.then((result) => console.log("OAuthProvider:", result))
.catch((error) => console.log("OAuthProvider::error:", error));
firebase
.auth()
.getRedirectResult()
.then((result) => console.log("RedirectResult:", result))
.catch((error) => console.log("RedirectResult::error:", error));
At first I go this auth/auth-domain-config-required error:
OAuthProvider::error: {
"code": "auth/auth-domain-config-required",
"message": "Be sure to include authDomain when calling firebase.initializeApp(), by following the instructions in the Firebase console."
}
I figured maybe this should be set to the OAuth provider I was wanting to login to, so I set authDomain in my firebase config to foo.myauthprovider.com, but when I called signInWithRedirect, it tried to load the following URL (where the apiKey is the API key of my firebase project), which failed to load:
https://foo.myauthprovider.com/__/auth/handler?apiKey=REDACTED&appName=%5BDEFAULT%5D&authType=signInViaRedirect&providerId=foo.example.com&redirectUrl=http%3A%2F%2Flocalhost%3A3000%2F&v=7.14.5
This /__/auth/handler URL is part of Firebase Auth's reserved URLs, which you can read more about at:
https://firebase.google.com/docs/hosting/reserved-urls#auth_helpers
And is explained a little better in this StackOverflow answer, but is basically what Firebase Auth uses to handle OAuth callbacks to avoid needing to expose sensitive credentials on the frontend, and so users don't need to implement their own handlers all the time):
Why does Firebase auth uses a "middleware" redirect before returning to my app?
Changing authDomain to the actual custom domain of my firebase project fixed that issue, and then resulted in the following auth/operation-not-allowed error when I tried to redirect:
RedirectResult::error: u {code: "auth/operation-not-allowed", message: "The identity provider configuration is not found.", a: null}

firebase auth share session/token between microservices

I working with firebase auth and I'm a bit confused on how to manage the authentication between different apps, in particular nextjs (main site, that use express too) api and react app (is a kind of dashboard). After reading a bit of documentation what I did (but I'm not sure is the right way) is to get the idToken on the main site with the client side library:
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
const currentUser = firebase.auth().currentUser.getIdToken();
currentUser.then(idToken => {
return axios.post("/auth/login", { idToken });
});
});
and make a request to nextjs/express to create the cookie sessions:
firebase
.auth()
.createSessionCookie(idToken, { expiresIn })
.then(
sessionCookie => {
res.cookie("session", sessionCookie, {
maxAge: expiresIn,
httpOnly: true
});
return res.end(JSON.stringify({ status: "success" }));
},
error => res.status(401).send(error)
);
then when I need to send a request to the api I'll pass the idtoken saved in the cookie and I verify the token in a middleware
const userInfo = await firebase.auth().verifySessionCookie(authToken);
I'm not implemented the react app yet but I think in that I'll just use the clientside library to do everything....My main doubt is the authentication between the nextjs/express and the api, I'm not sure if usin the sessioncookie is the right choise...do I need to send just the tokenId instead of the session cookie? do you have any suggestions?

Cloud Identity Platform: Are IdP-initiated SAML flows possible?

Google Cloud Identity Platform has documentation for Service Provider-initiated SAML auth flows. After searching the docs and online, I can't find anything about Identity Provider-initiated flows.
Are IdP-initiated SAML flows supported at all by Identity Platform? Assuming I'm using the firebase JS SDK, what would receiving the IdP SamlResponse POST even look like?
Thanks!
I just found that the current docs call out:
Currently, only service-provider (SP) initiated SAML flows via the web SDK are supported.
We can create our own ACS handler endpoint
route.post('/sso/callback', (samlResponse) => {
// 1. Use passport saml or saml2 to parse the saml response
// 2. Then create a claim
const userId = samlResponse.user.uid;
const additionalClaims = {
premiumAccount: true,
userGroups: []
};
admin
.auth()
.createCustomToken(userId, additionalClaims)
.then((customToken) => {
// Send token back to client
})
.catch((error) => {
console.log('Error creating custom token:', error);
});
});
and then in the client application
firebase.auth().signInWithCustomToken(token)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
// ...
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
// ...
});

How to set identifier on firebase authentication via custom token?

I just implemented the linkedin signup & login using firebase custom auth system through this https://firebase.google.com/docs/auth/admin/create-custom-tokens
It`s working but identifier on firebase is null.
How should I send it? Should I update it after creating the user?
I want to save it on create.
Thanks
Try this:
On your server, before minting the custom token, you can create the user with the email:
// Create the user with email first.
admin.auth().createUser({uid: uid, email: linkedinEmail})
.then(function(userRecord) {
// This will return custom token for that user above.
return admin.auth().createCustomToken(userRecord.uid);
})
.catch(function(error) {
// Some error.
});
Another option using client side code, is to set the email client side after signing in with custom token:
firebase.auth().signInWithCustomToken(customToken)
.then(function(result) {
return firebase.auth().currentUser.updateEmail(linkedinEmail);
})
.catch(function(error) {
// Some error occurred.
});
while creating custom token generate a unique UID at your own and save it in database
and as when there is someone trying o login with details match the credentials in database and fetch the correct UID and create a custom token with it. now with the help of custom token you can login
have a look at the code below
this is a well working code from my node.js project
const functions = require('firebase-functions');
const admin = require('firebase-admin');
module.exports = functions.https.onRequest((req, res) => {
//make a random and distinct uid
//and save it in database with the users credentials
//match them at the time of login
admin.auth().createCustomToken(uid)
.then(function(customToken) {
res.setHeader('Content-Type', 'application/json');
var error = false;
var result = {
"Error": error,
"CustomToken": customToken
};
res.send(JSON.stringify(result));
})
.catch(function(err) {
res.setHeader('Content-Type', 'application/json');
var error = true;
var result = {
"Error": error,
"Message": err
};
res.send(JSON.stringify(result));
});
});

Resources