Firebase REST API signInWithIdp and Apple SignIn Provider - MISSING_OR_INVALID_NONCE - react-native-firebase

I'm implementing Apple Sign In in a React Native App.
The sample I'm using works well within the Mobile App:
Apple Sign In - React Native Firebase
Just in case the link above changes, here is the code:
import auth from '#react-native-firebase/auth';
import { appleAuth } from '#invertase/react-native-apple-authentication';
async function onAppleButtonPress() {
// Start the sign-in request
const appleAuthRequestResponse = await appleAuth.performRequest({
requestedOperation: appleAuth.Operation.LOGIN,
requestedScopes: [appleAuth.Scope.EMAIL, appleAuth.Scope.FULL_NAME],
});
// Ensure Apple returned a user identityToken
if (!appleAuthRequestResponse.identityToken) {
throw 'Apple Sign-In failed - no identify token returned';
}
// Create a Firebase credential from the response
const { identityToken, nonce } = appleAuthRequestResponse;
const appleCredential = auth.AppleAuthProvider.credential(identityToken, nonce);
// Sign the user in with the credential
return auth().signInWithCredential(appleCredential);
}
In my backend Apps are only authorized to make calls if they use Firebase Access Tokens.
To get this to work, I am using the Google/Firebase REST API signInWithIdp. This works perfectly well for Twitter/Facebook/Google, but it doesn't for Apple.
What I/m doing is to use the Apple identityToken obtained here:
const { identityToken, nonce } = appleAuthRequestResponse;
And I make this call:
POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithIdp?key={key}
BODY:
{
"postBody":"id_token={identityToken}&providerId=apple.com",
"requestUri":"http://localhost",
"returnSecureToken": true
}
but I get:
{
"error": {
"code": 400,
"message": "MISSING_OR_INVALID_NONCE : Duplicate credential received. Please try again with a new credential.",
"errors": [
{
"message": "MISSING_OR_INVALID_NONCE : Duplicate credential received. Please try again with a new credential.",
"domain": "global",
"reason": "invalid"
}
]
}
}
Due to the lack of documentation I'm blocked on this one. :(
Any suggestions on how to eliminate this error are very welcome. :)

Here is the documentation to support 'Sign in with OAuth credential'. The examples it gives looks like this:
id_token=[GOOGLE_ID_TOKEN]&providerId=[google.com]
You can actually add a nonce parameter as well (which isn't documented!), for example:
id_token=ID_TOKEN&providerId=apple.com&nonce=NONCE
To figure this out, I had to use the SDK (I used iOS) and make the request. I used mitmproxy to read the network, and this is what it showed when putting in dummy data:

Related

react native facebook login using expo client: The App_id in the input_token did not match the Viewing App

I am using expo-facebook to integrate a Facebook login using expo and firebase. Everything looks to be working and I log into Facebook but get an OAuthException once I authenticate using Facebook as follows:
Unsuccessful debug_token response from Facebook: {"error":{"message":"(#100) The App_id in the input_token did not match the Viewing App","type":"OAuthException","code":100
I have gone through a lot of issues on Stack Overflow, GitHub and looked at expo documentation as well but to no avail.
I have configured the app id and secrets from Facebook into firebase as required as well as set up the OAuth redirect URI to my Facebook app configuration. The code I have put together to setup the login is as follows:
const signInWithFacebook = async () => {
try {
// const { type, token } = await Facebook.logInWithReadPermissionsAsync(
// facebookAppId,
// {
// permissions: ["public_profile"],
// }
// );
const appId = Constants.manifest.extra.facebook.appId;
const permissions = ["public_profile"]; // Permissions required, consult Facebook docs
await Facebook.initializeAsync({
appId: appId,
});
const { type, token } = await Facebook.logInWithReadPermissionsAsync({
permissions: permissions,
});
console.log(type);
console.log(token);
if (type === "success") {
await firebase
.auth()
.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
const credential = firebase.auth.FacebookAuthProvider.credential(token);
const facebookProfileData = await firebase
.auth()
.signInWithCredential(credential);
//this.onLoginSuccess.bind(this);
console.log(facebookProfileData);
}
} catch ({ message }) {
console.log(message);
alert(`Facebook Login Error: ${message}`);
}
};
I have also setup the relevant configurations in the app.json as follows:
"expo":{
"facebookScheme": "fb123243435566",
"facebookAppId": "123243435566",
"facebookDisplayName": "myapp"
}
The only aspect I am not sure about is where to grab the facebookScheme. Currenltly I have assumed it's fb+AppID. the documenatation mentioned here https://docs.expo.dev/versions/latest/sdk/facebook/
isn't clear. It states:
Configure app.json.
Add the field facebookScheme with your Facebook login redirect URL scheme found here under "4. Configure Your info.plist." It should look like "fb123456". If you do not do this, Facebook will not be able to redirect to your app after logging in.
But I am not sure how to grab that facebookScheme id. I suspect this is where the issue is as expo states that.
Expo Go from the Android Play Store will use the Facebook App ID that you provide, however, all Facebook API calls in the Expo Go from the iOS App Store will use Expo's own Facebook App ID. This is due to underlying configuration limitations.
so I am assuming the facebookScheme is some kind of workaround.
Although I am not sure if it's a working around for the ios standalone app or the expo managed.
Try this:
const { type, token } = await Expo.Facebook.logInWithReadPermissionsAsync(appId, {
permissions: [‘public_profile’, ‘email’],
behavior: Platform.OS === ‘android’ ? ‘web’ : ‘system’,
});
it should specify for the app to open a web browser on login
here's the ref:
https://forums.expo.dev/t/how-to-fix-standalone-android-expo-facebook-login/23922

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);
});
}

Unable to add chrome-extension "url" to firebase whitelisted domains

I've been loosely following the boilerplate in quickstart-js. I don't want to rely on Chrome's identify provider but rather want users to be able to sign in to my extension with their Google login using a popup so I haven't gone through the song and dance of requesting identity permissions in my manifest.json. My file is as follows:
{
"manifest_version": 2,
"name": "Firebase Auth in Chrome Extension Sample",
"description": "This sample shows how to authorize Firebase in a Chrome extension using a Google account.",
"version": "2.1",
"icons": {
"128": "firebase.png"
},
"browser_action": {
"default_icon": "firebase.png",
"default_popup": "credentials.html"
},
"background": {
"page": "background.html"
},
"content_security_policy":"script-src 'self' https://apis.google.com https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'"
}
I have baseline code that is similar to what's in quickstart-js. The relevant portion in my credentials.js is here:
/**
* Start the auth flow and authorizes to Firebase.
*/
async function startAuth() {
await firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
const provider = new firebase.auth.GoogleAuthProvider();
const res = await firebase.auth().signInWithPopup(provider);
}
// Starts the sign-in process.
function startSignIn() {
document.getElementById('quickstart-button').disabled = true;
if (firebase.auth().currentUser) {
firebase.auth().signOut();
} else {
startAuth();
}
}
window.onload = function() {
initApp();
};
This seems like it should work but constantly receive the following message:
Uncaught (in promise) Error: This chrome extension ID (chrome-extension://cckmbfklaloiadcphibealkhpncehpng) is not authorized to run this operation. Add it to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
According to the official docs, I should be able to whitelist my Chrome extension's ID in the Firebase control panel. I'm repeatedly given a success message but the extension "url" doesn't show up in my list of Authorized Domains and I keep getting the error message.
Is there somewhere else I need to add the Chrome Extension url?
This seems to have just been a regression. I reached out to Firebase support, got an answer a few days later, but by that point the bug was fixed.

Firebase client error: Custom token corresponds to a different audience

I'm using the Firebase Python AdminSDK to generate a custom token which a Javascript client uses to sign in to Firebase. When the JS client tries to authenticate with the custom token it gets the error "Custom token corresponds to a different audience".
The code given with the error: 'auth/custom-token-mismatch'.
Many Google'd answers regarding the "audience" mismatch reference Analytics. But I'm doing a Web project, not iOS or Android, so I can't use Analytics to manage audiences.
The SO answers I've read are listed at the end, below.
I captured the custom token and plugged it in to https://jwt.io/ and both the values and the instanciation/expiration times (an hour apart) look good:
Decoded custom token on jwt.io:
{
"claims": {},
"uid": "<myuniqueID",
"sub": "firebase-adminsdk-1knpr#firebase-<myproject>.iam.gserviceaccount.com",
"iss": "firebase-adminsdk-1knpr#firebase-<myproject>.iam.gserviceaccount.com",
"iat": 1540153710,
"aud": "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
"exp": 1540157310
}
Python server:
def getFirebaseInstance(): # For Firebase Python SDK
try:
currentDir_path = os.path.dirname(os.path.realpath(__file__))
cred = credentials.Certificate(currentDir_path + '/includeFirebaseServiceAccounts/firebase-<myprojectname>-firebase-adminsdk-1knpr-e1244dd261.json')
firebaseAdmin = firebase_admin.initialize_app(cred, { 'databaseURL': 'https://<myprojectname>.firebaseio.com', 'databaseAuthVariableOverride': {'uid':'<myuniqueServerID>'}})
if firebaseAdmin:
return(firebaseAdmin)
except:
raise
def firebaseClientToken(request):
try:
uid = "<myuniqueClientID>" # case sensitive
additional_claims = { }
token = auth.create_custom_token(uid,additional_claims)
return HttpResponse(token)
except Exception as err:
return HttpResponse("System error:" + str(err), status=406)
Javascript client:
(
function authClient2Firebase() {
$.ajax({
url: "firebaseClientToken/",
method: "POST",
success: function(response) { step2(response); },
error: function(xhr) { alert("There was an error loading a security check. Have you lost your internet connection? Detail:" + xhr.responseText); }
});
function step2(customToken) {
try {
firebase.auth().signInWithCustomToken(customToken).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
alert("There was an error with the secure login. \n\nDetail: " + errorMessage + '\nCode: ' + errorCode);
});
}
catch(err) {
alert(err);
}
console.log("authClient2Firebase.js: Firebase login succeeded!");
}
}
)();
My project under the Console "Settings" page does have a Web API key, but I don't see anywhere that it's used.
There's only one user, me, under the Console's "Settings"->"Users and Permissions" page.
There's only one service account listed on the Console "Settings"->"Service Accounts" page. I tried deleting all secrets on that page, generating a new one, then generating and installing a new blue-button "secret" (bad name, actually it generates a whole json credential object).
These are the domains listed in Console "Authentication" -> "Sign-in Method":
localhost Default
<myproject>.firebaseapp.com Default
127.0.0.1 Custom
auth.firebase.com Custom
The actual domain I'm using is localhost:8000, which can't be entered here.
SO answers consulted unsuccessfully:
The custom token corresponds to a different audience
(I'm not using a key, except what's stored in the ServiceAccount
credentials.)
Firebase token error, "The custom token corresponds to a different audience."
Firebase custom auth issue token different audienceenter
link description here (Close, but I'm not using a Node server and
not sure what he means by server "must belong to the same project"
since the Python server isn't registered in any way except through the
ServiceAccount credentials which I downloaded.)
Embarrassing but true, it turned out to be a simple oversight. When the JS client initialized itself as a Firebase app, before authenticating, it was using old credentials from a test environment.
// Initialize Firebase
var config = {
apiKey: "<WebAPI from Firebase console, 'Project Settings'>",
authDomain: "<myproject>.firebaseapp.com",
databaseURL: "https://<myproject>.firebaseio.com",
projectId: "<myproject>",
storageBucket: "<myproject>.appspot.com",
messagingSenderId: "<id from Console Project Settings>" // optional
};
firebase.initializeApp(config);

Call Google Play Developer API from Firebase Functions

I am trying to develop a server-side validation of my users' in-app purchases and subscriptions as recommended, and I want to use Firebase Functions for that. Basically it has to be an HTTP trigger function that receives a purchase token, calls the Play Developer API to verify the purchase, and then does something with the result.
However, calling many of the Google APIs (including Play Developer API) requires non-trivial authorization. Here's how I understand the required setup:
There has to be a GCP project with Google Play Developer API v2 enabled.
It should be a separate project, since there can be only one linked to Play Store in the Google Play Console.
My Firebase Functions project must somehow authenticate to that other project. I figured that using a Service Account is most suitable in this server-to-server scenario.
Finally, my Firebase Functions code must somehow obtain authentication token (hopefully JWT?) and finally make an API call to get a subscription status.
The problem is that absolutely no human-readable documentation or guidance on that is existent. Given that ingress traffic in Firebase is included in the free plan (so I assume they encourage using Google APIs from Firebase Functions), that fact is pretty disappointing. I've managed to find some bits of info here and there, but having too little experience with Google APIs (most of which required simply using an api key), I need help with putting it together.
Here's what I figured out so far:
I got a GCP project linked to the Play Store and with the API enabled. For some reason though, trying to test it in APIs Explorer results in an error "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console".
I made a Service Account and exported a JSON key, which contains the key to produce a JWT.
I also set up read permissions for that Service Account in Play Console.
I found a Node.JS client library for Google APIs, which is in alpha and has very sparse documentation (e.g. there's no obvious documentation on how to authenticate with JWT, and no samples on how to call the android publisher API). At the moment I'm struggling with that. Unfortunately I'm not super-comfortable with reading JS library code, especially when the editor doesn't provide the possibility to jump to highlighted functions' sources.
I'm pretty surprised this hasn't been asked or documented, because verifying in-app purchases from Firebase Functions seems like a common task. Has anyone successfully done it before, or maybe the Firebase team will step in to answer?
I figured it out myself. I also ditched the heavyweight client library and just coded those few requests manually.
Notes:
The same applies to any Node.js server environment. You still need the key file of a separate service account to mint a JWT and the two steps to call the API, and Firebase is no different.
The same applies to other APIs that require authentication as well — differing only in scope field of the JWT.
There are a few APIs that don't need you to exchange the JWT for an access token — you can mint a JWT and provide it directly in Authentication: Bearer, without a round trip to OAuth backend.
After you've got the JSON file with the private key for a Service Account that's linked to Play Store, the code to call the API is like this (adjust to your needs). Note: I used request-promise as a nicer way to do http.request.
const functions = require('firebase-functions');
const jwt = require('jsonwebtoken');
const keyData = require('./key.json'); // Path to your JSON key file
const request = require('request-promise');
/**
* Exchanges the private key file for a temporary access token,
* which is valid for 1 hour and can be reused for multiple requests
*/
function getAccessToken(keyData) {
// Create a JSON Web Token for the Service Account linked to Play Store
const token = jwt.sign(
{ scope: 'https://www.googleapis.com/auth/androidpublisher' },
keyData.private_key,
{
algorithm: 'RS256',
expiresIn: '1h',
issuer: keyData.client_email,
subject: keyData.client_email,
audience: 'https://www.googleapis.com/oauth2/v4/token'
}
);
// Make a request to Google APIs OAuth backend to exchange it for an access token
// Returns a promise
return request.post({
uri: 'https://www.googleapis.com/oauth2/v4/token',
form: {
'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion': token
},
transform: body => JSON.parse(body).access_token
});
}
/**
* Makes a GET request to given URL with the access token
*/
function makeApiRequest(url, accessToken) {
return request.get({
url: url,
auth: {
bearer: accessToken
},
transform: body => JSON.parse(body)
});
}
// Our test function
exports.testApi = functions.https.onRequest((req, res) => {
// TODO: process the request, extract parameters, authenticate the user etc
// The API url to call - edit this
const url = `https://www.googleapis.com/androidpublisher/v2/applications/${packageName}/purchases/subscriptions/${subscriptionId}/tokens/${token}`;
getAccessToken(keyData)
.then(token => {
return makeApiRequest(url, token);
})
.then(response => {
// TODO: process the response, e.g. validate the purchase, set access claims to the user etc.
res.send(response);
return;
})
.catch(err => {
res.status(500).send(err);
});
});
These are the docs I followed.
I think I found a slightly quicker way to do this... or at least... more simply.
To support scaling and keep index.ts from growing out of control... I have all the functions and globals in the index file but all the actual events are handled by handlers. Easier to maintain.
So here's my index.ts (I heart type safety):
//my imports so you know
import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";
import { SubscriptionEventHandler } from "./subscription/subscription-event-handler";
// honestly not 100% sure this is necessary
admin.initializeApp({
credential: admin.credential.applicationDefault(),
databaseURL: 'dburl'
});
const db = admin.database();
//reference to the class that actually does the logic things
const subscriptionEventHandler = new SubscriptionEventHandler(db);
//yay events!!!
export const onSubscriptionChange = functions.pubsub.topic('subscription_status_channel').onPublish((message, context) => {
return subscriptionEventHandler.handle(message, context);
});
//aren't you happy this is succinct??? I am!
Now... for the show!
// importing like World Market
import * as admin from "firebase-admin";
import {SubscriptionMessageEvent} from "./model/subscription-message-event";
import {androidpublisher_v3, google, oauth2_v2} from "googleapis";
import {UrlParser} from "../utils/url-parser";
import {AxiosResponse} from "axios";
import Schema$SubscriptionPurchase = androidpublisher_v3.Schema$SubscriptionPurchase;
import Androidpublisher = androidpublisher_v3.Androidpublisher;
// you have to get this from your service account... or you could guess
const key = {
"type": "service_account",
"project_id": "not going to tell you",
"private_key_id": "really not going to tell you",
"private_key": "okay... I'll tell you",
"client_email": "doesn't matter",
"client_id": "some number",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "another url"
};
//don't guess this... this is right
const androidPublisherScope = "https://www.googleapis.com/auth/androidpublisher";
// the handler
export class SubscriptionEventHandler {
private ref: admin.database.Reference;
// so you don't need to do this... I just did to log the events in the db
constructor(db: admin.database.Database) {
this.ref = db.ref('/subscriptionEvents');
}
// where the magic happens
public handle(message, context): any {
const data = JSON.parse(Buffer.from(message.data, 'base64').toString()) as SubscriptionMessageEvent;
// if subscriptionNotification is truthy then we're solid here
if (message.json.subscriptionNotification) {
// go get the the auth client but it's async... so wait
return google.auth.getClient({
scopes: androidPublisherScope,
credentials: key
}).then(auth => {
//yay! success! Build android publisher!
const androidPublisher = new Androidpublisher({
auth: auth
});
// get the subscription details
androidPublisher.purchases.subscriptions.get({
packageName: data.packageName,
subscriptionId: data.subscriptionNotification.subscriptionId,
token: data.subscriptionNotification.purchaseToken
}).then((response: AxiosResponse<Schema$SubscriptionPurchase>) => {
//promise fulfilled... grandma would be so happy
console.log("Successfully retrieved details: " + response.data.orderId);
}).catch(err => console.error('Error during retrieval', err));
});
} else {
console.log('Test event... logging test');
return this.ref.child('/testSubscriptionEvents').push(data);
}
}
}
There are few model classes that help:
export class SubscriptionMessageEvent {
version: string;
packageName: string;
eventTimeMillis: number;
subscriptionNotification: SubscriptionNotification;
testNotification: TestNotification;
}
export class SubscriptionNotification {
version: string;
notificationType: number;
purchaseToken: string;
subscriptionId: string;
}
So that's how we do that thing.

Resources