Auth0 is a flexible identity platform that lets you add authentication and authorization to your applications. It supports a wide range of use cases, from simple login/logout functionality to complex, multi-factor authentication flows.
Here’s how you can integrate Auth0 into your Single Page Applications (SPAs) built with React and Angular.
React SPA Integration
1. Install Auth0 Dependencies
First, add the necessary Auth0 packages to your React project:
npm install @auth0/auth0-react
# or
yarn add @auth0/auth0-react
2. Initialize Auth0Provider
Wrap your application with the Auth0Provider component. This component handles the authentication state and provides the necessary hooks and components for interacting with Auth0.
// src/index.js (or src/App.js)
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { Auth0Provider } from '@auth0/auth0-react';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Auth0Provider
domain="YOUR_AUTH0_DOMAIN"
clientId="YOUR_AUTH0_CLIENT_ID"
authorizationParams={{
redirect_uri: window.location.origin
}}
>
<App />
</Auth0Provider>
);
Replace YOUR_AUTH0_DOMAIN and YOUR_AUTH0_CLIENT_ID with your actual Auth0 domain and client ID, which you can find in your Auth0 dashboard under "Applications" -> "Your Application" -> "Settings".
3. Use Auth0 Hooks and Components
Auth0 provides hooks like useAuth0 to access authentication state and functions.
// src/App.js
import React from 'react';
import { useAuth0 } from '@auth0/auth0-react';
function App() {
const { loginWithRedirect, logout, user, isAuthenticated, isLoading } = useAuth0();
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{isAuthenticated ? (
<div>
<p>Hello, {user.name}!</p>
<button onClick={() => logout({ returnTo: window.location.origin })}>
Log Out
</button>
</div>
) : (
<button onClick={() => loginWithRedirect()}>Log In</button>
)}
</div>
);
}
export default App;
Angular SPA Integration
1. Install Auth0 Dependencies
Add the Auth0 Angular SDK to your Angular project:
ng add @auth0/auth0-angular
This command will also configure the necessary modules and providers in your app.module.ts file.
2. Configure AuthModule
In your app.module.ts, configure the AuthModule with your Auth0 domain and client ID.
// src/app/app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AuthModule } from '@auth0/auth0-angular'; // Import AuthModule
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AuthModule.forRoot({
domain: 'YOUR_AUTH0_DOMAIN',
clientId: 'YOUR_AUTH0_CLIENT_ID',
authorizationParams: {
redirect_uri: window.location.origin
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Replace YOUR_AUTH0_DOMAIN and YOUR_AUTH0_CLIENT_ID with your actual Auth0 credentials.
3. Use Auth0 Services and Directives
The Auth0 Angular SDK provides services like AuthService and directives for handling authentication.
// src/app/app.component.ts
import { Component } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular'; // Import AuthService
import { inject } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Welcome!</h1>
<button *ngIf="!(auth.isAuthenticated$ | async)" (click)="auth.loginWithRedirect()">Log In</button>
<button *ngIf="auth.isAuthenticated$ | async" (click)="auth.logout({ logoutParams: { returnTo: document.location.origin } })">Log Out</button>
<div *ngIf="auth.user$ | async as user">
<p>Hello, {{ user.name }}!</p>
</div>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
auth = inject(Auth AuthService); // Use inject for AuthService
}
In the template, we use the isAuthenticated$ observable from AuthService to conditionally render login/logout buttons and display user information when available.
Key Considerations:
- Callback URLs: Ensure that your Auth0 application’s "Allowed Callback URLs" in the Auth0 dashboard include the URLs where your SPA will handle the authentication callback (e.g.,
http://localhost:3000/callbackfor React, orhttp://localhost:4200for Angular). - Token Management: The Auth0 SDKs handle token storage (e.g., in
localStorageorsessionStorage) and refresh automatically. - API Calls: To make authenticated requests to your backend APIs, you’ll need to obtain an access token from Auth0 and include it in the
Authorizationheader of your API requests. The SDKs provide methods for this.
By following these steps, you can effectively integrate Auth0’s robust authentication and authorization capabilities into your React and Angular SPAs, streamlining user management and enhancing security.