When developing any product or app, it is essential to include login and signup features. These can be achieved using various methods such as email-password, social logins, or OTP. So if we want to implement all these login features in react native we must import the required SDKs and dependencies related to it.
However, to avoid this situation we can use other approaches. So Auth0 emerges as a superior solution for providing secure authentication and authorization services for your app. Below are some of the many features offered by Auth0.
➡️ Email-password login.
➡️ Social app login like Google, Facebook, Apple, Microsoft, etc.
➡️ Multi-factor authentication.
➡️ Forgot password and change password.
➡️ Biometric authentication.
➡️ UI customization.
Related read: What is Auth0? Features, Benefits And Its Implementation
If you do not possess an Auth0 account, you can sign up for one here on the official site of Auth0.
Now after setting up an account you have to go to the dashboard and need to check if any application is available or not. You can create a separate application for your app also. Here I have created a native-type app.
You will need Domain and Client ID when we implement login functionality.
yarn add react-native-auth0 cd ios && pod install
Go to ios/<project_name>/AppDelegate.m and add the following.
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options { return [RCTLinkingManager application:app openURL:url options:options]; }
Go to ios/<project_name> and open info.plist and add the following if not available.
<key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>None</string> <key>CFBundleURLName</key> <string>auth0</string> <key>CFBundleURLSchemes</key> <array> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> </array> </dict> </array>
To implement the necessary configurations, navigate to the android/app/build.gradle file and add the manifestPlaceholders block, which requires two parameters: the Auth0 domain and the android applicationId.
The code snippet below demonstrates how to do this:
android { defaultConfig { manifestPlaceholders = [auth0Domain: "your domain", auth0Scheme: "yourapplicationId"] } }
The callback URL is a crucial component in our application, as it allows Auth0 to redirect the user after a successful login, providing additional parameters that we can utilize for user verification and authentication.
To ensure its proper functioning, we need to add the callback URL in the Auth0 dashboard under “Your Application’s Settings” (Dashboard -> Applications -> Select Your Application -> Settings -> Application URIs).
Failing to add these URLs may result in an error message while implementing the login with the Auth0 feature. Hence, it is essential to include the correct callback URL in the Auth0 dashboard settings to enable smooth and secure user authentication and verification processes.
For iOS:
{PRODUCT_BUNDLE_IDENTIFIER}://{yourDomain}/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback
For Android:
{YOUR_APP_PACKAGE_NAME}://{yourDomain}/android/{YOUR_APP_PACKAGE_NAME}/callback
For example:
iOS : com.starwarsappdemo://dev-qa-stag.us.auth0.com/ios/com.starwarsappdemo/callback Android : com.starwarsappdemo://dev-qa-stag.us.auth0.com/android/com.starwarsappdemo/callback
The logout URL is an important component in our application that Auth0 utilizes to redirect the user after they have successfully logged out from the authentication server. To ensure the proper functioning of the logout feature, it is necessary to add the appropriate logout URL in the Auth0 dashboard. If the logout URL is not properly configured, there is a possibility of encountering an error message when implementing the logout feature.
For iOS:
{PRODUCT_BUNDLE_IDENTIFIER}://{yourDomain}/ios/{PRODUCT_BUNDLE_IDENTIFIER}/callback
For Android:
{YOUR_APP_PACKAGE_NAME}://{yourDomain}/android/{YOUR_APP_PACKAGE_NAME}/callback
For example:
iOS : com.starwarsappdemo://dev-qa-stag.us.auth0.com/ios/com.starwarsappdemo/callback
Android : com.starwarsappdemo://dev-qa-stag.us.auth0.com/android/com.starwarsappdemo/callback
To implement Auth0 authentication in our application, we need to import the Auth0Provider component from the Auth0 package. This component will be used to wrap up our entire application, enabling authentication functionalities throughout. The Auth0Provider component requires two parameter values: domain and clientId.
Below is an example of how you can add the necessary code:
import {Auth0Provider} from 'react-native-auth0'; const App = () => { try { return ( <Auth0Provider domain={“your app domain”} clientId={“your app client id”}> {/* Your Application code and Business Logic */} </Auth0Provider> ); } catch (error) { crashlytics().log('Error in App.'); crashlytics().recordError(error); } }; export default App;
To launch the Auth0 login UI, we can utilize the useAuth0 hook from the Auth0 package, which provides convenient access to various props and methods. One of these methods is authorized, which allows us to trigger the login process and display the Auth0 login UI.
Below is an example of how to implement this:
import {useAuth0} from 'react-native-auth0'; const {authorize, user, getCredentials, clearSession, clearCredentials} = useAuth0(); const onPressLoginWithAuth0 = async () => { try { await authorize(); } catch (e) { console.log(error) } }; return ( <ButtonComponent title={“Login”} onPress={onPressLoginWithAuth0} /> )
So it will open the UI as given below. You can signup and login also with Auth0 credentials.
After login, you will get user information in the user prop of the useAuth0 hook. Information can be like this.
{ "nickname": "johndoe", "name": "johndoe@yopmail.com", "picture": "https://s.gravatar.com/avatar/58aa4a5e3aad68d2d518857fee3ba691?s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fjo.png", "updated_at": "2023-07-27T10:41:13.453Z", "email": "johndoe@yopmail.com", "email_verified": false, "sub": "auth0|64c248a6adf0a94c33d0ad54" }
The Auth0 package provides an additional asynchronous method called getCredentials, which allows us to obtain further information related to the user’s authentication. By utilizing this method, we can retrieve various user-related data and authentication details.
Below are some examples of the information that can be obtained:
{ "idToken": "eyJhbGciOiJSUzI1Ni........", "tokenType": "Bearer", "scope": "openid profile email read:current_user offline_access", "accessToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6Ik.....", "refreshToken": "f9hwLH_55Eto0iU396RSopW....", "expiresIn": 1690543063 }
To Logout the user from the app we will use the clearCredentials and clearSession methods from the useAuth0 hook. So clearSession will remove the session from the authentication server and clearCredentials will remove the user credentials from the application.
const {authorize, user, getCredentials, clearSession, clearCredentials} = useAuth0(); const onPressLogOutWithAuth0 = () => { clearCredentials(); clearSession(); }; <ButtonComponent title={'Log Out'} onPress={onPressLogOutWithAuth0} />
The full code snippet is given below:
import {SafeAreaView, StyleSheet, Text, View} from 'react-native'; import React, {useEffect} from 'react'; import Colors from '../theme/Colors'; import {KeyboardAwareScrollView} from 'react-native-keyboard-aware-scroll-view'; import {isAndroid} from '../utils/Metrics'; import {ButtonComponent} from '../components'; import {useAuth0} from 'react-native-auth0'; import {Auth0Config} from '../networkConfig/Endpoints'; const Login = () => { const {authorize, user, getCredentials, clearSession, clearCredentials} = useAuth0(); useEffect(async () => { console.log('user-->', user); if (user) { console.log('user-->', await getCredentials()); } }, [user]); const onPressLoginWithAuth0 = async () => { try { await authorize({ scope: Auth0Config.scope, audience: Auth0Config.audience, prompt: 'login', }); } catch (e) {} }; const onPressLogOutWithAuth0 = () => { clearCredentials(); clearSession(); }; return ( <View style={styles.container}> <SafeAreaView /> <KeyboardAwareScrollView contentContainerStyle={styles.keyboardContainer} showsVerticalScrollIndicator={false} bounces={false} keyboardShouldPersistTaps="handled"> <Text style={styles.loginTitle}> {user ? 'Welcome to the demo' : 'Login to your account'} </Text> {user ? ( <View> <Text style={styles.loginDescription}>Email : {user?.email}</Text> <ButtonComponent title={'Log Out'} onPress={onPressLogOutWithAuth0} /> </View> ) : ( <ButtonComponent title={'Login'} onPress={onPressLoginWithAuth0} /> )} </KeyboardAwareScrollView> <SafeAreaView /> </View> ); }; export default Login;
You can find a recording of the demo here.
In this article, I have provided a comprehensive explanation of Auth0, its features, and the process of integrating Auth0 into a React Native application. We covered the configuration steps required for both iOS and Android platforms, ensuring a smooth setup process.
The integration process involves installing the necessary dependencies and pods, making iOS and Android configurations, and configuring callback URLs and logout URLs in the Auth0 dashboard.
Furthermore, I explained how developers can implement the login and logout functionalities within their React Native applications using the useAuth0 hook. By using this approach, developers can leverage Auth0’s authentication services to enhance the security and productivity of their apps.
Ronak is a React-Native developer with more than 4 years of experience in developing mobile applications for Android and iOS. He is dedicated to his work and passion. He worked in different kinds of application industries that have responsive designs. He also has knowledge of how to make an app with expo cli and react-native web and some basic understanding of react.js.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork