Skip to content

Handle Authentication with Auth0

Tyler Ruff edited this page Jul 2, 2022 · 3 revisions
  1. First, install Auth0 for Angular
npm install @auth0/auth0-angular
  1. Next, register and configure the authentication module (add the following to app.module.ts)
...
import { AuthModule } from '@auth0/auth0-angular';
...
imports: [
...
    // Import the module into the application, with configuration
    AuthModule.forRoot({
      domain: 'YOUR_DOMAIN',
      clientId: 'YOUR_CLIENT_ID'
    }),
...
],
  1. Then, you can add the login action to your application (start with component.ts):
...
import { AuthService } from '@auth0/auth0-angular';
...
export class ExampleComponent {
  // Inject the authentication service into your component through the constructor
  constructor(public auth: AuthService) {}
}
  1. Add the login action to your HTML file (component.html) as follows:
...
<button (click)="auth.loginWithRedirect()">Log in</button>
...
  1. Add the following to handle log-out:
...
<ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut">
  <button (click)="auth.logout()">
	Log out
  </button>
</ng-container>

<ng-template #loggedOut>
  <button (click)="auth.loginWithRedirect()">Log in</button>
</ng-template>
...
  1. Add the following to show user profile information:
<ul *ngIf="auth.user$ | async as user">
	<li>{{ user.name }}</li>
	<li>{{ user.email }}</li>
</ul>`
  1. Add the following to app-routing.module.ts to setup protected routes:
...
import { AuthGuard } from '@auth0/auth0-angular';
...
const routes: Routes = [
...
{ path: 'profile', component: ProfileComponent, canActivate: [AuthGuard] },
...
];
...

Sources