BUY THE FULL SOURCE CODE
Welcome folks today in this blog post we will be integrating auth0
library in angular 14 to integrate google oauth2
login and display profile info
of user in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
app using the below command as shown below
ng new sampleapp
cd sampleapp
npm i @auth0/auth-angular
And now you will see the below directory
structure of the final react.js project as shown below
And after that you need to go app.module.ts
file and copy paste the following code
app.module.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { AuthModule } from '@auth0/auth0-angular'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, // Import the module into the application, with configuration AuthModule.forRoot({ domain: '##replaceyourdomainname##', clientId: '##replaceyourclientid##', authorizationParams: { redirect_uri: window.location.origin } }), ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
Here you need to replace your own details
from the auth0 dashboard as shown below
Here you need to replace the localhost:4200
url to the callback url and also to the web origin
and also to the logout url also.
Now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import { DOCUMENT } from '@angular/common'; import { Component, Inject } from '@angular/core'; import { AuthService } from '@auth0/auth0-angular'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angularauth'; constructor(@Inject(DOCUMENT) public document: Document, public auth: AuthService) {} } |
As you can see we are importing the authService
from the auth0 package. And then we are passing this service inside the constructor.
Now we need to copy paste the below code inside the app.component.html
file to display the profile
of the user and also we will be having the button to login
with google using redirect
or popup
. And here we are using the ngIf
condition to make sure we display the logout
button if the user is authenticated and show the login
button if the user is logged out.
app.component.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<ng-container *ngIf="auth.isAuthenticated$ | async; else loggedOut"> <ul *ngIf="auth.user$ | async as user"> <li>{{ user.name }}</li> <li>{{ user.email }}</li> <li><img src="{{user.picture}}"/></li> </ul> <button (click)="auth.logout({ logoutParams: { returnTo: document.location.origin } })"> Log out </button> </ng-container> <ng-template #loggedOut> <button (click)="auth.loginWithRedirect()">Log in</button> </ng-template> |
BUY THE FULL SOURCE CODE