Firebase Authentication in Android Application
Firebase Authentication is a powerful tool that allows developers to add user authentication and authorization to their applications quickly.
In this tutorial, we will explore how to integrate Firebase Authentication into a React Native app using the react-native-firebase
library.
We'll cover the basic setup and demonstrate how to implement common authentication features like email/password login.
Prerequisites:
Before we begin, make sure you have the following prerequisites installed:
- Node.js
- React Native CLI
- Firebase account
Step 1: Set Up a Firebase Project
To get started, create a new Firebase project or use an existing one. Visit the Firebase Console and Follow the prompts to set up your project.
https://console.firebase.google.com
- Click on Add Project.
2. Create a Project, type your Project name aand click on continue.
3. Enable Google analytics, this is optional but recommended, you can skip or disable this.
4. If you enabled google analytics then you have to select Google analytics account. So here you can click on Default account for Firebase. or you can create new account also.
5. It will show like this once your project is ready then click on continue.
6. Then you’ll redirect to this screen. We need only for Android for now, so we will click on Android icon.
7. Then you will land on this screen.
8. Here you have add Android package name which you’ll find in the android -> app -> build.gradle (applicationId)
9. After fill package name and nickname you have to add SHA1 so for this you can run this command in React-Native App directory
cd android && ./gradlew signingReport
10. And then you will see SHA1 like this so copy from here and paste in the above form and click on Register App.
11. After click on register app you’ll redirect to 2nd step. Here you have to dowlaod google-services.json file at this location:
Your Project folder -> android folder -> app folder
12. After download above file at the mentioned location, click on next. And you’ll redirected to 3rd step. Here you have to add these lines to android/build.gradle file, at this location:
Your Project folder -> android folder -> build.gradle file
13. And these lines in android/app/build.gradle file:
Your Project folder -> android folder -> app folder -> build.gradle file
And then reinstall your app in device or emulator to sync with the gradle files. After this click on next.
14. After click on next you’ll redirected to the 4th and last step. Here you only have to click on continue to console button. And we are good to go.
15. Then You’ll redirect to the Dashboard of firebase console and here you’ll see this and you have to click on Authentication.
16. After click on Aunthentication you’ll see this, Here Click on Get started.
17. After Get started, Under Sign-in method tab click on Email/pasword.
18. Here make sure to enable the Email/password service under Authentication in Sign in tab and hit save.
Here we are done with the Firebase configurations, now let’s jump to the VS code and Install some dependencies.
Step 2: Install Dependencies
To use Firebase auth, Register, Login and Logout Feature we have to install these 2 libraries:
npm install @react-native-firebase/app
npm install @react-native-firebase/auth
Step 3: Register with Firebase auth
Email/password registration is a common method on applications. This requires the user to provide an email address and secure password. Users can register using a method called createUserWithEmailAndPassword
.
The createUserWithEmailAndPassword
performs two operations; first creating the user if they do not already exist, and then signing them in.
import auth from '@react-native-firebase/auth';
import React, {useState} from 'react';
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const onRegister = () => {
if (password !== confirmPassword) {
Alert.alert("Password don't match.");
return;
}
if (email && password) {
auth()
.createUserWithEmailAndPassword(email, password)
.then(() => {
console.log('User account created & signed in!');
})
.catch(error => {
if (error.code === 'auth/email-already-in-use') {
console.log('That email address is already in use!');
}
if (error.code === 'auth/invalid-email') {
console.log('That email address is invalid!');
}
console.error(error);
});
} else {
Alert.alert('Please fill in details!');
}
};
Step 4: Login with Firebase auth
Email/password sign in is a common method for user sign in on applications. This requires the user to provide an email address and secure password. Users can sign in to an existing account with signInWithEmailAndPassword
.
Ensure the “Email/Password” sign-in provider is enabled on the Firebase Console.
import auth from '@react-native-firebase/auth';
import React, {useState} from 'react';
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const onLogin = () => {
if (email && password) {
auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
console.log('response :', response);
})
.catch(error => {
if (error.code === 'auth/wrong-password') {
Alert.alert('Your password is wrong!');
} else {
Alert.alert(`${error}`);
}
console.log('error :', error);
});
}
};
Once successfully created and/or signed in, onAuthStateChanged
listeners will trigger an event with the User
details.
Step 5: Listening to authentication state
In most scenarios using Authentication, you will want to know whether your users are currently signed-in or signed-out of your application.
The module provides a method called onAuthStateChanged
which allows you to subscribe to the users current authentication state, and receive an event whenever that state changes.
import auth from '@react-native-firebase/auth';
import React, {useState} from 'react';
const [user, setUser] = useState();
const onAuthStateChanged = (user) => setUser(user);
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber;
}, []);
<NavigationContainer>
<Stack.Navigator screenOptions={{ headerShown: false }}>
{user ?
<Stack.Screen name="MainScreen" component={MainScreen} />
:
<>
<Stack.Screen name="LoginScreen" component={LoginScreen} />
<Stack.Screen name="RegisterScreen" component={RegisterScreen} />
</>
}
</Stack.Navigator>
</NavigationContainer>
In above code snippit I’m referring to stack navigations, If user logged in and have data in user state then I’m redirecting screen to the Main Screen else redirecting to the login screen.
Step 6: Signing out
If you’d like to sign the user out of their current authentication state, call the signOut
method:
import auth from '@react-native-firebase/auth';
const onLogout = () => {
auth()
.signOut()
.then(() => Alert.alert('User signed out!'))
.catch(error => console.log('error :', error));
};
Once successfully created and/or signed in, any onAuthStateChanged
listeners will trigger an event with the user
parameter being a null
value.
Conclusion
In this tutorial, we explored how to integrate Firebase Authentication into a React Native app using the react-native-firebase
library. We covered the basic setup and demonstrated how to implement email/password authentication.
Firebase Authentication provides a robust and secure solution for user authentication in mobile applications.
Remember to handle error cases properly and provide appropriate feedback to users during the authentication process.
Feel free to explore the official Firebase Authentication documentation (https://firebase.google.com/docs/auth) for more in-depth information and additional features you can implement in your app.
I hope this tutorial has provided you with a good starting point for integrating Firebase Authentication into your React Native app.
Happy coding!