19
User Authentication in Angular App using Auth0
The focal point of this aide is to assist engineers with figuring out how to get an Angular application by executing client verification. You'll improve an Angular starter application to rehearse the accompanying security ideas:
- Configure Auth0
- Install the Auth0 Angular SDK
- Add Login to Your Application
- Add Logout to Your Application
- Show User Profile Information
At the point when you pursued Auth0, another application was made for you, or you might have made another one. You will require a few insights concerning that application to speak with Auth0. You can get these subtleties from the "Application Settings" area in the Auth0 dashboard.
Run the accompanying order inside your undertaking registry to introduce the Auth0 Angular SDK:
npm install @auth0/auth0-angular
// environment.ts
export const environment = {
production: false,
auth: {
domain: 'YOUR_DOMAIN',
clientId: 'YOUR_CLIENT_ID'
}
};
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
// Import the module from the SDK
import { AuthModule } from '@auth0/auth0-angular';
import { environment } from 'src/environments/environment';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
// Import the module into the application, with configuration
AuthModule.forRoot(environment.auth)
],
bootstrap: [AppComponent],
})
export class AppModule {}
Import the AuthService type from the SDK, and to create a login button using the loginWithRedirect() & logout() methods from the AuthService service class.
import { Component, OnInit } from '@angular/core';
// Import the AuthService type from the SDK
import { AuthService } from '@auth0/auth0-angular';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
// Inject the authentication service into your component through the constructor
constructor(public auth: AuthService) {}
ngOnInit(): void {
}
}
<header>
<h3>Auth0 Angular</h3>
<div *ngIf="auth.isAuthenticated$ | async; else loggedOut">
<button (click)="auth.logout()">
Log out
</button>
</div>
<ng-template #loggedOut>
<button (click)="auth.loginWithRedirect()">Log in</button>
</ng-template>
</header>
The Auth0 Angular SDK assists you with recovering the profile data related with signed in clients rapidly in whatever part you need, for example, their name or profile picture. The profile data is accessible through the user$ detectable uncovered by the AuthService administration, you have to import the AuthService in the component as we seen above in header.component.ts and get data in html file of the component.
<div *ngIf="auth.user$ | async as user">
<h2>Welcome</h2>
<p>{{ user.email }}</p>
</div>
Github Source:
https://github.com/muhammadawaisshaikh/angular-auth0
19