In this tutorial, you will learn how to integrate Auth0 into an eCommerce application.
Users can sign up or log in (including social login).
This tutorial assumes that you have already completed the section “eCommerce Project – Checkout Form – Save the Order to Database” in the Full Stack Angular Spring Boot Tutorial course.
- Create a developer account on Auth0
- Create Application and provide Application Information
- Create API
- Install Auth0 dependencies
- Create/Update
my-app-config.ts - Add Login Status Component
- Update
app.module.ts - Add
auth-interceptor.service.ts - Spring Boot – Backend Changes
- Run the Application
- Open: https://developer.auth0.com/
- Sign up.
- In Auth0 Developer Account, select
Applications > + Create Application - Name:
My Angular App - Choose
Single Page Applications - Click Create
PROVIDE APP INFORMATION
Add Application URIs:
- Allowed Callback URLs:
http://localhost:4200/login/callback - Allowed Logout URLs:
http://localhost:4200 - Allowed Web Origins:
http://localhost:4200 - Allowed Origins (CORS):
http://localhost:4200
Click Save
CREATE API
- In Auth0 Developer Account, select
Applications > API > + Create API - Name:
My Spring Boot App - Identifier:
http://localhost:8080 - Click Create
Run the following command in the Angular app console:
npm install @auth0/auth0-angularexport default {
auth: {
domain: "<<UPDATE-WITH-YOUR-DEV-DOMAIN>>",
clientId: "<<UPDATE-WITH-YOUR-APP-CLIENT-ID>>",
authorizationParams: {
redirect_uri: "http://localhost:4200",
audience: "http://localhost:8080",
},
},
httpInterceptor: {
allowedList: [
'http://localhost:8080/api/orders/**',
'http://localhost:8080/api/checkout/purchase'
],
},
}Generate component:
ng generate component components/login-statusFile: login-status.component.ts
import { DOCUMENT } from '@angular/common';
import { Component, Inject } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
@Component({
selector: 'app-login-status',
templateUrl: './login-status.component.html',
styleUrl: './login-status.component.css'
})
export class LoginStatusComponent {
isAuthenticated: boolean = false;
profileJson: string | undefined;
userEmail: string | undefined;
storage: Storage = sessionStorage;
constructor(private auth: AuthService, @Inject(DOCUMENT) private doc: Document) {}
ngOnInit(): void {
this.auth.isAuthenticated$.subscribe((authenticated: boolean) => {
this.isAuthenticated = authenticated;
console.log('User is authenticated: ', this.isAuthenticated);
});
this.auth.user$.subscribe((user) => {
this.userEmail = user?.email;
this.storage.setItem('userEmail', JSON.stringify(this.userEmail));
console.log('User ID: ', this.userEmail);
});
}
login() {
this.auth.loginWithRedirect();
}
logout(): void {
this.auth.logout({ logoutParams: { returnTo: this.doc.location.origin } });
}
}Update app.module.ts with the following additions:
import { AuthGuard, AuthHttpInterceptor, AuthModule } from '@auth0/auth0-angular';
import myAppConfig from './config/my-app-config';
import { AuthInterceptorService } from './services/auth-interceptor.service';
@NgModule({
...
imports: [
...
AuthModule.forRoot({
...myAppConfig.auth,
httpInterceptor: {
...myAppConfig.httpInterceptor,
},
}),
],
providers: [
ProductService,
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptorService,
multi: true,
},
],
...
})
export class AppModule { }Generate service:
ng generate service services/auth-interceptorFile: auth-interceptor.service.ts
import {
HttpEvent,
HttpHandler,
HttpInterceptor,
HttpRequest,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { from, lastValueFrom, Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthInterceptorService implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return from(this.handleAccess(request, next));
}
private async handleAccess(request: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
const securedEndpoints = ['http://localhost:8080/api/orders'];
if (securedEndpoints.some((url) => request.urlWithParams.includes(url))) {
await this.auth.getAccessTokenSilently().forEach((token) => {
console.log('Access Token: ', token);
request = request.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
},
});
});
}
return await lastValueFrom(next.handle(request));
}
}File: application.properties
## issuer url must ends with "/"
okta.oauth2.issuer=https://<<UPDATE-WITH-YOUR-DOMAIN-NAME>>/
okta.oauth2.client-id=<<UPDATE-WITH-YOUR-APP-CLIENT-ID>>
okta.oauth2.audience=http://localhost:8080- Sign up using email or social login
- Verify member and orders
- Logout
© luv2code LLC
www.luv2code.com




