Why is App Check Admin SDK rejecting debug tokens? - android

I am using App Check with my Flutter Android debug App to validate my app with my Cloud Run Node API. I followed the steps required to get and add the debug token to the Firebase Console Admin UI but it is rejecting my requests.
Here is my backend code:
const authenticate = async (req, res, next) => {
const appCheckToken = req.header('X-Firebase-AppCheck');
if (!appCheckToken) {
res.status(401);
return next('Unauthorized');
}
try {
const appCheckClaims = await firebaseAdmin.appCheck().verifyToken(appCheckToken);
// If verifyToken() succeeds, continue with the next middleware
// function in the stack.
return next();
} catch (err) {
res.status(401);
return next('Unauthorized');
}
}
And my main method in Flutter:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await FirebaseAppCheck.instance.activate(
webRecaptchaSiteKey: 'recaptcha-v3-site-key',
// Default provider for Android is the Play Integrity provider. You can use the "AndroidProvider" enum to choose
// your preferred provider. Choose from:
// 1. debug provider
// 2. safety net provider
// 3. play integrity provider
androidProvider: AndroidProvider.debug,
);
runApp(const MyApp());
}

Related

Connecting to cloud function running on emulator from android emulator in react native

I am building an application and using firebase for the backend. I used react-native-firebase to use firebase in my application. I have developed a login cloud function
exports.login = functions.https.onCall((data, context) => {
console.log("data", data);
console.log("context", context);
return "Login successful";
});
On running npm run serve in the functions folder I am getting these configurations in my console.
Console output after running npm run serve inside functions folder for firebase
Also I have added the following code to connect to the cloud function from my android emulator running the application.
import functions from "#react-native-firebase/functions"
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const handleLogin = () => {
// console.log(email, password);
functions()
.useFunctionsEmulator("URL")
.httpsCallable("login")({ email, password })
.then((response) => {
alert(response);
});
}
for URL I have tried "http://localhost:5001/" as it is the port on which the functions emulator is listening
Port on which cloud functions is listening. But on running the application I am getting this error
Error on clicking login button in app console. I tried searching for the error but nothing relevant comes up. Any help will be appreciated.
These are my cloud functions that I have defined
exports.helloWorld = functions.https.onRequest((request, response) => {
functions.logger.info("Hello logs!", { structuredData: true });
response.send("Hello from Firebase!");
});
exports.signup = functions.https.onRequest((request, response) => {
console.log("request", request);
response.send("SignUp successfull");
});
exports.login = functions.https.onCall((data, context) => {
console.log("data", data);
console.log("context", context);
return "SignIn successfull";
});
I was able to work it out finally
const handleLogin = async () => {
functions().useFunctionsEmulator("http://localhost:5001")
const response = await functions().httpsCallable("login")({ email, password });
console.log("response", response);
}
This is all the code required to successfully call cloud function locally inside an emulator from your running android emulator.

React Native Google Signin with multiple accounts

I have a react native application which uses google sign in. currently, I can sign in with one of my google accounts which my mobile signed in, but I need to do an OAuth for another google account in my google accounts stack, this is to get the API access I need the serverAuthToken for the secondary accounts
The library I'm using for google login - https://github.com/react-native-community/google-signin
What I have done till now:
const firebaseGoogleLogin = async () => {
try {
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
if (userInfo) {
await storeToken(userInfo);
// eslint-disable-next-line no-console
console.log('User info retrieved during login', userInfo);
}
// create a new firebase credential with the token
// eslint-disable-next-line max-len
const credential = firebase.auth.GoogleAuthProvider.credential(userInfo.idToken, userInfo.accessToken);
// login with credential
// eslint-disable-next-line no-unused-vars
const firebaseUserCredential = await firebase.auth().signInWithCredential(credential);
console.log('Logged in')
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log('sign in cancelled', error);
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log('signin in progress error', error);
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log('play services are not available or outdated', error);
} else {
console.log('some other error occurred', error);
}
}
};
Result for the above code:
This is the code I used to login with my primary Google account, after logging in I'm triggering the play services modal to sign in with other accounts using the above, but the modal closes with loading a sec and gets closed, shows me Logged in in the log, since I have already logged, in the play services automatically bypass the option to select an account
The above problem occurs only in android, ios seems fine even after logging in with an account
Was trying to do a hack if there isn't a way for multiple account authorization since an account already signed in it is bypassing the play service modal, I'm thinking to logout the user once he signed into my application (process level) and inside the main activity, I can have the play services still? is this the right way to do!
Probably you have fixed the issue. I think the method below will solve your problem. Call this after logout.
signOut = async () => {
try {
await GoogleSignin.revokeAccess();
await GoogleSignin.signOut();
this.setState({ user: null }); // Remember to remove the user from your app's state as well
} catch (error) {
console.error(error);
}
};
First import { GoogleSignin } from "#react-native-google-signin/google-signin"; in your logout file
If you're using firbase authentication after
auth().signOut().then(() => {
GoogleSignin.revokeAccess();
});

Developer Error while logging in with google in react-native + firebase

I am trying to log in with google in my project build in react-native. I am testing it on a real android device. But it is giving DEVELOPER ERROR while signing in. I have added the SHA 1 certificate of the debug.keystore formed in android/app directory of the project to the project setting in firebase console.
ERROR:
This is the error image
The following is how I am implementing it.
import { GoogleSignin } from '#react-native-community/google-signin';
import auth from '#react-native-firebase/auth';
const GoogleLogin = () => {
useEffect(() => {
GoogleSignin.configure({
webClientId: '************************', // From Firebase Console Settings
});
}, [])
async function onGoogleButtonPress() {
console.log('i am running on google login function')
// Get the users ID token
const { idToken } = await GoogleSignin.signIn();
console.log('idToken :', idToken)
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}
const handleSignIn = () => {
onGoogleButtonPress()
.then(() => {
console.log('Signed in with google.')
})
.catch((err) => console.log('error while signing in with Google:', err))
}
return (
<Button
title="Google Sign-In"
onPress={handleSignIn}
/>
)
}
In handleSignIn method, it is going in .catch.
Any help is appreciated
Try also passing in the accessToken.
See https://firebase.google.com/docs/reference/node/firebase.auth.GoogleAuthProvider#credential.
At least one of ID token and access token is required.
async function onGoogleButtonPress() {
console.log('i am running on google login function')
// Get the users ID token
const { idToken, accessToken } = await GoogleSignin.signIn();
console.log('idToken :', idToken, 'accessToken :', accessToken)
// Create a Google credential with the token
const googleCredential = auth.GoogleAuthProvider.credential(idToken, accessToken);
// Sign-in the user with the credential
return auth().signInWithCredential(googleCredential);
}

Not receiving notifications from Firebase in Android, but connection is established

Versions
#react-native-firebase/app: 6.3.4
#react-native-firebase/messaging: 6.3.4
react: 16.9.0
react-native: 0.61.4
Inside my App.js file, I'm registering for notifications like this
...
import messaging from '#react-native-firebase/messaging';
const App: () => React$Node = () => {
const registerForNotifications = async () => {
const granted = await messaging().requestPermission();
if (granted) {
console.log('User granted messaging permissions!');
} else {
console.log('User declined messaging permissions :(');
}
await messaging().registerForRemoteNotifications();
const unsubscribe = messaging().onMessage(async remoteMessage => {
console.log('FCM Message Data:', remoteMessage.data);
});
const token = await messaging().getToken();
console.log({token});
return unsubscribe;
};
useEffect(() => {
SplashScreen.hide();
registerForNotifications();
}, []);
...
}
and it shows me that user granted messaging permissions, and it seems to register correctly for remote notifications, and finally I get the token, which seems to be ok and connected.
In firebase messaging console, I send a new notification and in possible targets it seems to be my user (Inside Cloud messaging menu)
So I do not see any error, but for some reason I sent multiple notifications, and I don't receive them, it doesn't matter if the app is open or close. I don't know what to do because I cannot see any error.

How to delete Firebase Cloud Messaging Token when user Log-Out of the React Native application?

I use React Native FCM for messaging, and when the user logs out the application I want to delete the FCM token so that the user doesn't get Notified again.
Below is my code for logout.
_signOutAsync = async () => {
this.logoutEvent()
API.post('customer/auth/logout', null, {
headers: {
Authorization:
'Bearer ' + (await AsyncStorage.getItem(Config.ACCESS_TOKEN))
}
}).then((response) => {
console.log(response)
})
this.clearData()
}
Thanks.
Simply add below given code in your logout function -
for react-native-firebase <= v5.x.x
firebase.messaging().deleteToken()
for > 5.x.x or using #react-native-firebase/messaging
import messaging from '#react-native-firebase/messaging';
messaging().deleteToken()
await firebase.messaging().deleteToken();
is the solution.
BUT, if you get the same token even after deleting, install the npm package react-native-restart, and do the below step to get a new token
messaging()
.deleteToken(undefined,'*')
.then(() => {
RNRestart.Restart();
Install the npm package react-native-restart and Simply call like this:
const logoutAndClearAsyncStorage = async () => {
try {
await AsyncStorage.clear()
await firebase.messaging().deleteToken().then(() => {
RNRestart.Restart()
navigation.replace('LoginStack', { screen: 'WelcomeScreen' });
})
} catch (error) {
console.log(error, 'logout')
}
};
Recently I try to use FCM too, and found the issue usually due to the function comes from, i.e. where to import the functions.
I think you already have installed firebase package, call the function below will trigger delete token on firebase.
import { getMessaging, deleteToken } from 'firebase/messaging';
const messaging = getMessaging(firebaseApp);
deleteToken(messaging);

Categories

Resources