Ionic & Capacitor (React)
This tutorial demonstrates how to add user login with Auth0 to an Ionic React & Capacitor application. We recommend that you log in to follow this quickstart with examples configured for your account.
I want to integrate with my app
15 minutesI want to explore a sample app
2 minutesGet a sample configured with your account settings or check it out on Github.
Getting started
This quickstart assumes you already have an Ionic application up and running with Capacitor. If not, check out the Using Capacitor with Ionic Framework guide to get started with a simple app, or clone our sample apps.
You should also be familiar with the Capacitor development workflow.
Configure Auth0
Get Your Application Keys
When you signed up for Auth0, a new application was created for you, or you could have created a new one. You will need some details about that application to communicate with Auth0. You can get these details from the Application Settings section in the Auth0 dashboard.
You need the following information:
- Domain
- Client ID
Configure Callback URLs
A callback URL is a URL in your application where Auth0 redirects the user after they have authenticated. The callback URL for your app must be added to the Allowed Callback URLs field in your Application Settings. If this field is not set, users will be unable to log in to the application and will get an error.
Go to the Application Settings section in your Auth0 dashboard and set your Callback URL in the Allowed Callback URLs box.
You should set the Allowed Callback URL to:
YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
Was this helpful?
Configure Logout URLs
A logout URL is a URL in your application that Auth0 can return to after the user has been logged out of the authorization server. This is specified in the returnTo
query parameter. The logout URL for your app must be added to the Allowed Logout URLs field in your Application Settings. If this field is not set, users will be unable to log out from the application and will get an error.
You should set the Allowed Logout URLs to
YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback
Was this helpful?
Configure Origins
To be able to make requests from your application to Auth0, set the following Allowed Origins in your Application Settings.
capacitor://localhost, http://localhost
Was this helpful?
These origins are required for iOS and Android respectively.
Lastly, be sure that the Application Type for your application is set to Native in the Application Settings.
Install the Auth0 React SDK
Run the following command within your project directory to install the Auth0 React SDK:
npm install @auth0/auth0-react
Was this helpful?
The SDK exposes methods and variables that help you integrate Auth0 with your React application idiomatically using React Hooks or Higher-Order Components.
Install Capacitor plugins
This quickstart and sample make use of some of Capacitor's official plugins. Install these into your app using the following command:
npm install @capacitor/browser @capacitor/app
Was this helpful?
@capacitor/browser
- allows us to interact with the device's system browser, and is used to open the URL to Auth0's authorizaction endpoint@capacitor/app
- allows us to subscribe to high-level app events, useful for handling callbacks from Auth0
Configure the Auth0Provider component
Under the hood, the Auth0 React SDK uses React Context to manage the authentication state of your users. One way to integrate Auth0 with your React app is to wrap your root component with an Auth0Provider
that you can import from the SDK.
Open src/index.tsx
and wrap the App
component in the Auth0Provider
component.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';
ReactDOM.render(
<Auth0Provider
domain="YOUR_DOMAIN"
clientId="YOUR_CLIENT_ID"
redirectUri="YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback"
>
<App />
</Auth0Provider>,
document.getElementById('root')
);
Was this helpful?
The Auth0Provider
component takes the following props:
domain
: The "domain" value present under the "Settings" of the application you created in your Auth0 dashboard, or your custom domain if using Auth0's Custom Domains featureclientId
: The "client ID" value present under the "Settings" of the application you created in your Auth0 dashboardredirectUri
: The URL to where you'd like to redirect your users after they authenticate with Auth0.
Checkpoint
Now that you have configured Auth0Provider
, run your application to verify that the SDK is initializing correctly, and your application is not throwing any errors related to Auth0.
Add Login to Your Application
In a Capacitor application, the Capacitor's Browser plugin should be used to perform a redirect to the Auth0 Universal Login Page. Use the buildAuthorizeUrl
function to get the URL to redirect the user.
Add a new file LoginButton.tsx
with the following code:
import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/react';
const LoginButton: React.FC = () => {
const { buildAuthorizeUrl } = useAuth0();
const login = async () => {
// Ask auth0-react to build the login URL
const url = await buildAuthorizeUrl();
// Redirect using Capacitor's Browser plugin
await Browser.open({ url });
};
return <IonButton onClick={login}>Log in</IonButton>;
};
export default LoginButton;
Was this helpful?
This component:
- defines a template with a simple button that logs the user in when clicked
- uses
buildAuthorizeUrl
to construct a URL to Auth0's Universal Login page - uses Capacitor's Browser plugin to open the URL and show the login page to the user
Handling the callback
Once a user has logged in using the Universal Login Page, they will be redirected back to your app using a URL with a custom URL scheme. The appUrlOpen
event must be handled within your app, where handleRedirectCallback
can be called to initialize the authentication state within the SDK.
Add the following useEffect
hook to your main App
component:
// Import Capacitor's app and browser plugins, giving us access to `addListener` and `appUrlOpen`,
// as well as the bits needed for Auth0 and React
import { App as CapApp } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import { useEffect } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
// ...
const App: React.FC = () => {
// Get the callback handler from the Auth0 React hook
const { handleRedirectCallback } = useAuth0();
useEffect(() => {
// Handle the 'appUrlOpen' event and call `handleRedirectCallback`
CapApp.addListener('appUrlOpen', async ({ url }) => {
if (url.includes('state') && (url.includes('code') || url.includes('error'))) {
await handleRedirectCallback(url);
}
// No-op on Android
await Browser.close();
});
}, [handleRedirectCallback]);
// ..
};
Was this helpful?
Checkpoint
Add the LoginButton
component to your application, as well as the handler for the "appUrlOpen" event to your App
component. When you click the login button, verify that your application redirects you to the Auth0 Universal Login Page and that you can now log in or sign up using a username and password or a social provider.
Once that's complete, verify that Auth0 redirects you back to your application.
Add Logout to Your Application
Now that you can log in, you need a way to log out. To do this, the user must be redirected to the Auth0 logout endpoint in the browser in order to clear their browser session. Again, Capacitor's Browser plugin should be used to perform this redirect so that the user does not leave your app and otherwise receive a suboptimal experience.
To achieve this with Ionic and Capacitor in conjunction with the Auth0 SDK, the steps are:
- Use the SDK to build the URL to the logout endpoint by calling
buildLogoutUrl
- Call the
logout
function on the SDK, settinglocalOnly: true
. This will clear the internal state of the SDK but not perform the redirect to Auth0 - Redirect the user to the logout endpoint using
Browser.open
Create a new file LogoutButton.tsx
and add the following code to the file. Then, add the LogoutButton
component to your app.
import { useAuth0 } from '@auth0/auth0-react';
import { Browser } from '@capacitor/browser';
import { IonButton } from '@ionic/react';
// This should reflect the URL added earlier to your "Allowed Logout URLs" setting
// in the Auth0 dashboard.
const logoutUri = 'YOUR_PACKAGE_ID://YOUR_DOMAIN/capacitor/YOUR_PACKAGE_ID/callback';
const LogoutButton: React.FC = () => {
const { buildLogoutUrl, logout } = useAuth0();
const doLogout = async () => {
// Open the browser to perform a logout
await Browser.open({ url: buildLogoutUrl({ returnTo: logoutUri }) });
// Ask the SDK to log out locally, but not do the redirect
logout({ localOnly: true });
};
return <IonButton onClick={doLogout}>Log out</IonButton>;
};
export default LogoutButton;
Was this helpful?
Checkpoint
Add the LogoutButton
component to your application. When you click it, verify that your Ionic application redirects you the address you specified as one of the "Allowed Logout URLs" in the "Settings" and that you are no longer logged in to your application.
Show User Profile Information
The Auth0 React SDK helps you retrieve the profile information associated with logged-in users quickly in whatever component you need, such as their name or profile picture, to personalize the user interface. The profile information is available through the user
property exposed by the useAuth0()
hook. Take this Profile
component as an example of how to use it:
import { useAuth0 } from '@auth0/auth0-react';
const Profile: React.FC = () => {
const { user, isLoading } = useAuth0();
// If the SDK is not ready, or a user is not authenticated, exit.
if (isLoading || !user) return null;
return (
<div>
<img src={user.picture} alt={user.name} />
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
};
export default Profile;
Was this helpful?
The user
property contains sensitive information and artifacts related to the user's identity. As such, its availability depends on the user's authentication status. To prevent any render errors, use the isAuthenticated
property from useAuth0()
to check if Auth0 has authenticated the user before React renders any component that consumes the user
property. Ensure that the SDK has completed loading before accessing the isAuthenticated
property, by checking that isLoading
is false
.
Checkpoint
Add the Profile
component to your application, and verify that you can display the user.name
or any other user
property within a component correctly after you have logged in.