-
-
Notifications
You must be signed in to change notification settings - Fork 0
Handle Authentication with Auth0
Tyler Ruff edited this page Jul 2, 2022
·
3 revisions
- First, install Auth0 for Angular
npm install @auth0/auth0-angular
- 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'
}),
...
],
- 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) {}
}
- Add the login action to your HTML file (component.html) as follows:
...
<button (click)="auth.loginWithRedirect()">Log in</button>
...
- 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>
...
- Add the following to show user profile information:
<ul *ngIf="auth.user$ | async as user">
<li>{{ user.name }}</li>
<li>{{ user.email }}</li>
</ul>`
- 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] },
...
];
...
Join the Blazed Development Group today to get involved in open source collaborative projects.
Discover our FREE learning resources, the Blazed University, Web Development School, and Blazed City.