Angular User Authentication with Auth0 🛡️

Hello, Am Udhay (OO-dhy)

Hello Auth0! 👋

Auth0 is a flexible, drop-in solution to add authentication and authorization services to your applications. Your team and organization can avoid the cost, time, and risk that comes with building your own solution to authenticate and authorize users.

  • Integrate with app written in any language / framework
  • 30+ SDKs
  • Supports Social Identity Providers
  • Multi Factor Authentication

 

Config Auth0 in Angular App🔧

  • Clone Pokemon application from GitHub: https://github.com/askudhay/pokemon-app.
  • Add Auth0 support to the Angular application you just cloned.
  • Create JSON file to store Auth0 domain and Client ID
# Add Auth0 support to Angular project
cd pokemon-app
ng add @auth0/auth0-angular
.
.
.
# JSON to store domain and Client ID
touch auth_config.json
  • Copy domain and client ID from your auth0 application to auth_config.json
{
  "domain": "askudhay.us.auth0.com",
  "clientId": "6rQ6l8lsxDiUh24L1ZaB0VmdEeZamhAp"
}

Config Auth0 in Angular App🔧

Update environment.ts🔧

  • Open environment.ts in Angular app and update with below code.
  • This is just for Non prod environment. Update similarly in enviornment.prod.ts if you want to deploy Prod grade app
import { domain, clientId } from '../../auth_config.json';

export const environment = {
  production: false,
  auth: {
    domain,
    clientId,
    redirectUri: window.location.origin,
  },
};

Register & Configure Auth0 Module🔧

Register Auth0 Module in app,module.ts as shown below:

import { AuthModule } from '@auth0/auth0-angular';
import { environment as env } from '../environments/environment';
.
@NgModule({
  declarations: [...],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    .
    .
    // add and initialize AuthModule
    AuthModule.forRoot({
      ...env.auth,
    }),
  ],
.

Secure Routes in Angular🔧

Add Auth0 "AuthGuard" to canActivate Routes property. It handles Login and redirect back User to requested path.

.
.
import { AuthGuard } from '@auth0/auth0-angular';

const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  .
  .
  .
  {
    path: 'pokemon/:id',
    loadChildren: () =>
      import('./pokemon-stats/pokemon-stats.module').then(
        (m) => m.PokemonStatsModule
      ),
    canActivate: [AuthGuard],
  },
];
.
.

Secure Routes in Angular🔧

Let's explore Auth0 - Identity providers and Multi Factor Authentication

Demo

Code - 

Demo - 

Checkout my previous

Useful links

ngThanks!

Angular User Authentication with Auth0 🛡️

By Udhayakumar G

Angular User Authentication with Auth0 🛡️

This is my recent talk for Angular Online Meetup on "Let's create an Angular Storybook! 🎨". Reach me @askudhay on Twitter. Happy learning! Thanks.

  • 1,931