How to Add Login, Sign-Up, and Route Guards to Angular Apps (original) (raw)

angular logo

typescript logo

Angular Authentication By Example

Updated on June 21, 2024

Options

Standard Components

Standalone Components

This TypeScript guide will help you learn how to secure an Angular application using token-based authentication. You'll learn how to use the Angular framework to implement the following security features:

This guide uses the Auth0 Angular SDK, which provides developers with a high-level API to handle many authentication implementation details. You can now secure your Angular applications following security best practices while writing less code.

Quick Angular Setup

With the help of Auth0, you don't need to be an expert on identity protocols, such as OAuth 2.0 or OpenID Connect, to understand how to secure your web application stack.

You first integrate your Angular application with Auth0. Your application will then redirect users to an Auth0 customizable login page when they need to log in. Once your users log in successfully, Auth0 redirects them back to your Angular app, returning JSON Web Tokens (JWTs) with their authentication and user information.

Get the Angular Starter Application

We have created a starter project using the Angular CLI to help you learn Angular security concepts through hands-on practice. You can focus on building Angular components and services to secure your application.

Start by cloning the spa_angular_typescript_hello-world repository on its starter branch:

git clone -b starter [email protected]:auth0-developer-hub/spa_angular_typescript_hello-world.git

Once you clone the repo, make spa_angular_typescript_hello-world your current directory:

cd spa_angular_typescript_hello-world

Install the Angular project dependencies as follows:

This starter Angular project offers a functional application that consumes data from an external API to hydrate the user interface. For simplicity and convenience, the starter project simulates the external API locally using json-server. Later on, you'll integrate this Angular application with a real API server using a backend technology of your choice.

The compatible API server runs on http://localhost:6060 by default. As such, to connect your Angular application with that API server, create a .env file under the root project directory:

Populate .env with the following environment variables:

API_SERVER_URL=http://localhost:6060

This project uses an npm script to integrate the content of the .env file with the Angular framework. Check out the set-env.ts file:

const { writeFile, existsSync, mkdirSync } = require('fs');

const { promisify } = require('util');

const path = require('path');

const dotenv = require('dotenv');

dotenv.config();

const writeFilePromisified = promisify(writeFile);

const targetPath = './src/environments/environment.ts';

const envConfigFile = `export const environment = {

production: false,

api: {

serverUrl: '${process.env['API_SERVER_URL']}',

},

};

`;

(async () => {

try {

await ensureDirectoryExistence(targetPath);

await writeFilePromisified(targetPath, envConfigFile);

} catch (err) {

console.error(err);

throw err;

}

})();

function ensureDirectoryExistence(filePath: string) {

var dirname = path.dirname(filePath);

if (existsSync(dirname)) {

return;

}

ensureDirectoryExistence(dirname);

mkdirSync(dirname);

return;

}

This script uses the dotenv package to load environment variables from a .env file into process.env. The script then uses a string template to create the content of the ./src/environments/environment.ts file. It then writes that file with the prescribed content into the Angular project.

The env npm script defined in package.json runs the set-env.ts script using ts-node. However, you don't have to execute npm run env directly. The start npm script will run that for you before you start the Angular development server.

As such, execute the following command to run the Angular application:

Next, execute the following command to run the JSON server API:

You are ready to start implementing user authentication in this Angular project. First, you'll need to configure the Angular application to connect successfully to Auth0. Afterward, you'll use the Auth0 Angular SDK to protect routes, display user profile information, and request protected data from an external API server to hydrate some of the application pages.

Configure Angular with Auth0

Follow these steps to get started with the Auth0 Identity Platform quickly:

Sign up and create an Auth0 Application

Authentication For DevelopersGet Auth0 for free with up to 7,500 active users and unlimited logins. No credit card required.Authentication For DevelopersGet Auth0 for free with up to 7,500 active users and unlimited logins. No credit card required.Create a Free Auth0 Account→

A free account also offers you:

During the sign-up process, you create something called an Auth0 Tenant, representing the product or service to which you are adding authentication.

Once you sign in, Auth0 takes you to the Dashboard. In the left sidebar menu, click on "Applications".

Then, click the "Create Application" button. A modal opens up with a form to provide a name for the application and choose its type. Use the following values:

Auth0 Angular Code Sample

Application Type

Single Page Web Applications

Single Page Web Applications

Click the "Create" button to complete the process. Your Auth0 application page loads up.

In the next step, you'll learn how to help Angular and Auth0 communicate.

What's the relationship between Auth0 Tenants and Auth0 Applications?

Let's say that you have a photo-sharing Angular app called "NG-Gram". You then would create an Auth0 tenant called ng-gram. From a customer perspective, NG-Gram is that customer's product or service.

Now, say that NG-Gram is available on three platforms: web as a single-page application and Android and iOS as a native mobile application. If each platform needs authentication, you need to create three Auth0 applications to provide the product with everything it needs to authenticate users through that platform.

NG-Gram users belong to the Auth0 NG-Gram tenant, which shares them across its Auth0 applications.

Create a communication bridge between Angular and Auth0

When using the Auth0 Identity Platform, you don't have to build login forms. Auth0 offers a Universal Login Page to reduce the overhead of adding and managing authentication.

How does Universal Login work?

Your Angular application will redirect users to Auth0 whenever they trigger an authentication request. Auth0 will present them with a login page. Once they log in, Auth0 will redirect them back to your Angular application. For that redirecting to happen securely, you must specify in your Auth0 Application Settings the URLs to which Auth0 can redirect users once it authenticates them.

As such, click on the "Settings" tab of your Auth0 Application page, locate the "Application URIs" section, and fill in the following values:

http://localhost:4040/callback

The above value is the URL that Auth0 can use to redirect your users after they successfully log in.

The above value is the URL that Auth0 can use to redirect your users after they log out.

Using the Auth0 Angular SDK, your Angular application will make requests under the hood to an Auth0 URL to handle authentication requests. As such, you need to add your Angular application origin URL to avoid Cross-Origin Resource Sharing (CORS) issues.

Scroll down and click the "Save Changes" button.

Do not close this page yet. You'll need some of its information in the next section.

Add the Auth0 configuration variables to Angular

From the Auth0 Application Settings page, you need the Auth0 Domain and Client ID values to allow your Angular application to use the communication bridge you created.

What exactly is an Auth0 Domain and an Auth0 Client ID?

Domain

When you created a new Auth0 account, Auth0 asked you to pick a name for your tenant. This name, appended with auth0.com, is your Auth0 Domain. It's the base URL that you will use to access the Auth0 APIs and the URL where you'll redirect users to log in.

Client ID

Each application is assigned a Client ID upon creation, which is an alphanumeric string, and it's the unique identifier for your application (such as q8fij2iug0CmgPLfTfG1tZGdTQyGaTUA). You cannot modify the Client ID. You will use the Client ID to identify the Auth0 Application to which the Auth0 SPA SDK needs to connect.

Warning: Another critical piece of information present in the "Settings" is the Client Secret. This secret protects your resources by only granting tokens to requestors if they're authorized. Think of it as your application's password, which must be kept confidential at all times. If anyone gains access to your Client Secret, they can impersonate your application and access protected resources.

Head back to your Auth0 application page and click on the "Settings" tab.

Locate the "Basic Information" section and follow these steps to get the Auth0 Domain and Auth0 Client ID values:

Auth0 application settings to enable user authentication

When you enter a value in the input fields present on this page, any code snippet that uses such value updates to reflect it. Using the input fields makes it easy to copy and paste code as you follow along.

As such, enter the "Domain" and "Client ID" values in the following fields to set up your single-page application in the next section:

These variables let your Angular application identify itself as an authorized party to interact with the Auth0 authentication server.

Now, update the .env file under the Angular project directory as follows:

API_SERVER_URL=http://localhost:6060

AUTH0_DOMAIN=AUTH0-DOMAIN

AUTH0_CLIENT_ID=AUTH0-CLIENT-ID

AUTH0_CALLBACK_URL=http://localhost:4040/callback

Once you reach the "Call a Protected API from Angular" section of this guide, you'll learn how to use API_SERVER_URL along with an Auth0 Audience value to request protected resources from an external API that is also protected by Auth0. For now, the application is using json-server to mock the API.

Update the set-env.ts script file to integrate these new Auth0 environment variables from .env into your Angular src/environments/environment.ts file:

const { writeFile, existsSync, mkdirSync } = require('fs');

const { promisify } = require('util');

const path = require('path');

const dotenv = require('dotenv');

dotenv.config();

const writeFilePromisified = promisify(writeFile);

const targetPath = './src/environments/environment.ts';

const envConfigFile = `export const environment = {

production: false,

auth0: {

domain: '${process.env['AUTH0_DOMAIN']}',

clientId: '${process.env['AUTH0_CLIENT_ID']}',

authorizationParams: {

  redirect_uri: '${process.env['AUTH0_CALLBACK_URL']}',

},

errorPath: '/callback',

},

api: {

serverUrl: '${process.env['API_SERVER_URL']}',

},

};

`;

(async () => {

try {

await ensureDirectoryExistence(targetPath);

await writeFilePromisified(targetPath, envConfigFile);

} catch (err) {

console.error(err);

throw err;

}

})();

function ensureDirectoryExistence(filePath: string) {

var dirname = path.dirname(filePath);

if (existsSync(dirname)) {

return;

}

ensureDirectoryExistence(dirname);

mkdirSync(dirname);

return;

}

You're creating an auth0 object using the configuration values from the Auth0 application you created in the Auth0 Dashboard: Auth0 Domain and Client ID.

Additionally, you use the authorizationParams configuration object to define the query parameters that Angular needs to include on its calls to the Auth0 /authorize endpoint. You define the redirect_uri property within this object to specify the URL from your Angular application to where Auth0 should redirect your users after they successfully log in.

Later, you'll use the auth0 object properties to configure the AuthModule from the Auth0 Angular SDK using the forRoot() pattern.

Restart your Angular development server to re-generate the src/environments/environment.ts file:

Handle the Auth0 post-login behavior

Notice that the Auth0 Callback URL, AUTH0_CALLBACK_URL, points to http://localhost:4040/callback, which is the URL that Auth0 uses to redirect your users after they successfully log in. For this Angular application, you'll render a simple page component for the /callback route.

Start by creating a CallbackModule file under the src/app/features directory using the Angular CLI:

ng g module features/callback --routing

Next, use the Angular CLI to create a CallbackComponent under the src/app/features/callback directory and declare it in the CallbackModule:

ng g component features/callback --module=features/callback/callback.module.ts --skip-tests --style=none --standalone=false

Update the CallbackModule to include the SharedModule in its imports array:

import { NgModule } from '@angular/core';

import { CommonModule } from '@angular/common';

import { SharedModule } from '@app/shared';

import { CallbackComponent } from './callback.component';

import { CallbackRoutingModule } from './callback-routing.module';

@NgModule({

declarations: [CallbackComponent],

imports: [CommonModule, SharedModule, CallbackRoutingModule],

})

export class CallbackModule {}

Update the CallbackRoutingModule to set CallbackComponent as the default route:

import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

import { CallbackComponent } from './callback.component';

const routes: Routes = [

{

path: "",

component: CallbackComponent,

}

];

@NgModule({

imports: [RouterModule.forChild(routes)],

exports: [RouterModule]

})

export class CallbackRoutingModule { }

Populate the src/app/features/callback/callback.component.html template file as follows:

<ng-content></ng-content>

The CallbackComponent will only render the navigation bar and an empty content container to help you create a smooth transition between a route with no content, /callback, to a route with content, such as the /profile page.

The next step is to lazy-load your CallbackModule using the Angular router.

Locate the src/app/app-routing.module.ts file and update it like so:

import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [

{

path: '',

pathMatch: 'full',

loadChildren: () =>

  import('./features/home/home.module').then((m) => m.HomeModule),

},

{

path: 'profile',

loadChildren: () =>

  import('./features/profile/profile.module').then((m) => m.ProfileModule),

},

{

path: 'public',

loadChildren: () =>

  import('./features/public/public.module').then((m) => m.PublicModule),

},

{

path: 'protected',

loadChildren: () =>

  import('./features/protected/protected.module').then(

    (m) => m.ProtectedModule

  ),

},

{

path: 'admin',

loadChildren: () =>

  import('./features/admin/admin.module').then((m) => m.AdminModule),

},

{

path: 'callback',

loadChildren: () =>

  import('./features/callback/callback.module').then(

    (m) => m.CallbackModule

  ),

},

{

path: '**',

loadChildren: () =>

  import('./features/not-found/not-found.module').then(

    (m) => m.NotFoundModule

  ),

},

];

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule],

})

export class AppRoutingModule {}

What are the benefits of using a callback page?

Implementing a page that specializes in handling the user redirection from the Auth0 Universal Login Page to your application (the callback event) has some benefits:

Once you add a login and logout button to this app, you can verify this user experience improvement by using your browser's developer tools. In the case of Google Chrome, you could do the following:

If you are not convinced yet, let's explore more details on the impact of this strategy.

Imagine that you want to redirect your users to the /profile after they log in. If you were to use the root URL of your Angular application, http://localhost:4040, as the Auth0 Callback URL, you may hurt the user experience when the user's connection is slow or when you are lazy loading the /profile route:

Additionally, when you load the home page, /, you may trigger logic that fetches data from an external API or runs any other business logic related to hydrating the home page. If your intention is to show the users a /profile page after they log in, there's no need or value to run any of that home page business logic that won't impact the rendering of the /profile page. Instead, you may increase your operational costs by running unnecessary logic when any of your users log in. In that case, it's better to handle the Auth0 redirect in a minimal and performant specialized route, /callback.

Install and Set Up the Auth0 Angular SDK

Execute the following command to install the Auth0 Angular SDK:

npm install --save @auth0/auth0-angular

The Auth0 Angular SDK exposes several methods, variables, and types that help you integrate Auth0 with your Angular application idiomatically, including an authentication module and service.

Update the src/app/app.module.ts file as follows to import the AuthModule from the Auth0 Angular SDK into your AppModule and configure it using data from your environment module:

import { provideHttpClient } from '@angular/common/http';

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AuthModule } from '@auth0/auth0-angular';

import { environment as env } from '../environments/environment';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

@NgModule({

declarations: [AppComponent],

imports: [

BrowserModule,

AppRoutingModule,

AuthModule.forRoot({

  ...env.auth0,

}),

],

providers: [provideHttpClient()],

bootstrap: [AppComponent],

})

export class AppModule {}

You use the forRoot() pattern to configure AuthModule, which takes an object with the domain, clientId, and authorizationParams properties. You create that configuration object by spreading the env.auth object.

User authentication is a mechanism to control who can access your application. You can integrate your Angular application with Auth0 to prevent users who have not logged in from accessing a /profile or /admin route.

If users want to access a guarded route from your application, Auth0 will stop them and ask them to present their credentials. If Auth0 can verify who they are and that they are supposed to go in there, Auth0 will let them in.

The authentication process won't happen within your Angular application layer when using Auth0. Your Angular application will redirect your users to the Auth0 Universal Login page, where Auth0 asks them for credentials and redirects them back to your application with the result of the authentication process.

Auth0 and Angular connection set

You have completed setting up an authentication module that your Angular application can consume. All that is left is for you to continue building up the starter project throughout this guide by implementing Angular components that trigger and manage the authentication flow.

Feel free to dive deeper into the Auth0 Documentation to learn more about how Auth0 helps you save time implementing and managing identity.

The steps on how to build an Angular login form or login page are complex. You can save development time by using a login page hosted by Auth0 that has a built-in login form that supports different types of user authentication: username and password, social login, and Multi-Factor Authentication (MFA). You just need to create a button that takes users from your Angular application to the login page.

Start by generating a LoginButtonComponent file under the src/app/shared/components/buttons directory and register it the SharedModule using the Angular CLI:

ng g component shared/components/buttons/login-button --module=shared/shared.module.ts --inline-template --skip-tests --style=none --flat --export --standalone=false

Populate src/app/shared/components/buttons/login-button.component.ts like so:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-login-button',

template: `

<button class="button__login" (click)="handleLogin()">Log In</button>

`,

})

export class LoginButtonComponent {

private auth = inject(AuthService);

handleLogin(): void {

this.auth.loginWithRedirect({

  appState: {

    target: '/profile',

  },

});

}

}

Within the LoginButtonComponent definition, this.auth.loginWithRedirect() is a method exposed by AuthService that performs a redirect to the Auth0 /authorize endpoint to kickstart the authentication process. You can pass a configuration object to this method to customize the login experience.

By setting up the value of appState.target to /profile, you are telling the Auth0 Angular SDK the following: When my users log in with Auth0 and return to my Angular application, take them from the default callback URL path, /callback, to the "Profile" page, /profile. If you don't specify this appState.returnTo option, your users will be redirected by default to the / path after they log in.

In the next section, you'll configure this method to create a button that your users can click on to sign up for your application.

Add User Sign-Up to Angular

The process on how to build an Angular sign-up form is much more complex. However, you can use a sign-up form hosted by Auth0 that has a built-in password strength verification.

You can create a button that takes users from your Angular application to the sign-up page by specifying the screen_hint=signup property in the authorizationParams configuration object of the loginWithRedirect() method:

authorizationParams: {

screen_hint: "signup",

}

This loginWithRedirect() method is a wrapper from the Auth0 SPA SDK method of the same name. As such, you can use the RedirectLoginOptions document from the Auth0 SPA SDK to learn more details on these configuration options.

To see this in practice, generate a SignupButtonComponent file under the src/app/shared/components/buttons directory and register it with the SharedModule using the Angular CLI:

ng g component shared/components/buttons/signup-button --module=shared/shared.module.ts --inline-template --skip-tests --style=none --flat --export --standalone=false

Populate src/app/shared/components/buttons/signup-button.component.ts like so to define a sign-up button component:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-signup-button',

template: `

<button class="button__sign-up" (click)="handleSignUp()">Sign Up</button>

`,

})

export class SignupButtonComponent {

private auth = inject(AuthService);

handleSignUp(): void {

this.auth.loginWithRedirect({

  appState: {

    target: '/profile',

  },

  authorizationParams: {

    screen_hint: 'signup',

  },

});

}

}

Using the Auth0 Signup feature requires you to enable the Auth0 New Universal Login Experience in your tenant.

Open the Universal Login section of the Auth0 Dashboard and choose the "New" option under the "Experience" subsection.

Auth0 Universal Login Experience options

Scroll down and click on the "Save Changes" button.

The difference between the login and sign-up user experience will be more evident once you integrate those components with your Angular application and see them in action. You'll do that in the following sections.

Add User Logout to Angular

You can log out users from your Angular application by logging them out of their Auth0 sessions using the logout() method from the Auth0 Angular SDK.

Generate a LogoutButtonComponent file under the src/app/shared/components/buttons directory and register it the SharedModule using the Angular CLI:

ng g component shared/components/buttons/logout-button --module=shared/shared.module.ts --inline-template --skip-tests --style=none --flat --export --standalone=false

Populate src/app/shared/components/buttons/logout-button.component.ts like so:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

import { DOCUMENT } from '@angular/common';

@Component({

selector: 'app-logout-button',

template: `

<button class="button__logout" (click)="handleLogout()">Log Out</button>

`,

})

export class LogoutButtonComponent {

private auth = inject(AuthService);

private doc = inject(DOCUMENT);

handleLogout(): void {

this.auth.logout({

  logoutParams: {

    returnTo: this.doc.location.origin,

  },

});

}

}

When using the logout() method, the Auth0 Angular SDK clears the application session and redirects to the Auth0 /v2/logout endpoint to clear the Auth0 session under the hood.

As with the login method, you can pass an object argument to logout() to customize the logout behavior of the Angular application. You can define a logoutParams property on that configuration object to define parameters for the /v2/logout call. This process is fairly invisible to the user. See logoutParams for more details on the parameters available.

Here, you pass the logoutParams.returnTo option to specify the URL where Auth0 should redirect your users after they log out. Right now, you are working locally, and your Auth0 application's "Allowed Logout URLs" points to http://localhost:4040.

However, if you were to deploy your Angular application to production, you need to add the production logout URL to the "Allowed Logout URLs" list and ensure that Auth0 redirects your users to that production URL and not localhost. Setting logoutParams.returnTo to window.location.origin will do just that.

A best practice when working with Auth0 is to have different tenants for your different project environments. For example, it's recommended for developers to specify a production tenant. A production tenant gets higher rate limits than non-production tenants. Check out the "Set Up Multiple Environments" Auth0 document to learn more about how to set up development, staging, and production environments in the Auth0 Identity Platform.

Render Components Conditionally

In this section, you'll learn how to render Angular components conditionally based on the status of the Auth0 Angular SDK or the authentication status of your users.

Render the authentication buttons conditionally

The Angular starter application features a desktop and mobile navigation experience.

When using your Angular application on a viewport large enough to fix a desktop or tablet experience, you'll see a navigation bar at the top of the page.

When using a viewport that fits the screen constraints of a mobile device, you'll see a menu button at the top-right corner of the page. Tapping or clicking on the menu button opens a modal that shows you the different pages that you can access in the application.

In this section, you'll expose the button components that trigger the login, sign-up, and logout events through these page navigation elements.

Let's start with the desktop navigation user experience. You'll show both the login and sign-up buttons on the navigation bar when the user is not logged in. Naturally, you'll show the logout button when the user is logged in.

Create an isAuthenticated$ variable in the NavBarButtonsComponent to implement the user experience defined above:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-nav-bar-buttons',

templateUrl: './nav-bar-buttons.component.html',

})

export class NavBarButtonsComponent {

private auth = inject(AuthService);

isAuthenticated$ = this.auth.isAuthenticated$;

}

Next, update the src/app/shared/components/navigation/desktop/nav-bar-buttons.component.html as follows to conditionally show and hide login, sign-up, and logout buttons:

<ng-container *ngIf="isAuthenticated$ | async; else unAuthenticated">

    <app-logout-button></app-logout-button>

</ng-container>

<ng-template #unAuthenticated>

    <app-signup-button></app-signup-button>

    <app-login-button></app-login-button>

</ng-template>

Auth0's isAuthenticated$ value reflects the authentication state of your users as tracked by the Auth0 Angular SDK plugin. This value is true when the user has been authenticated and false when not. As such, you can use the isAuthenticated$ observable to render UI elements conditionally depending on the authentication state of your users, as you did above.

The mobile navigation experience works in the same fashion, except that the authentication-related buttons are tucked into the mobile menu modal.

Update src/app/shared/components/navigation/mobile/mobile-nav-bar-buttons.component.ts as follows:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-mobile-nav-bar-buttons',

templateUrl: './mobile-nav-bar-buttons.component.html',

})

export class MobileNavBarButtonsComponent {

private auth = inject(AuthService);

isAuthenticated$ = this.auth.isAuthenticated$;

}

Next, update the src/app/shared/components/navigation/mobile/mobile-nav-bar-buttons.component.html as follows to conditionally show and hide login, sign-up, and logout buttons:

<ng-container *ngIf="isAuthenticated$ | async; else unAuthenticated">

    <app-logout-button></app-logout-button>

</ng-container>

<ng-template #unAuthenticated>

    <app-signup-button></app-signup-button>

    <app-login-button></app-login-button>

</ng-template>

Go ahead and try to log in. Your Angular application redirects you to the Auth0 Universal Login page. You can use the form to log in with a username and password or a social identity provider like Google. Notice that this login page also gives you the option to sign up.

New Auth0 Universal Login Experience Form

However, when you click the sign-up button from your application directly, Angular takes you to the Signup page, where your users can sign up for the Angular application. Try it out!

New Auth0 Universal Login Experience Signup Page

Notice that when you finish logging in or signing up, Auth0 redirects you to your Angular app, but the login and sign-up buttons may briefly show up before the logout button renders. You'll fix that next.

Render the application conditionally

The user interface flashes because your Angular app doesn't know if Auth0 has authenticated the user yet. Your Angular application will know the user authentication status after the Auth0 Angular SDK initializes.

To fix that UI flashing, use the isLoading$ observable exposed by the AuthService that emits a boolean value to render a loader in the AppComponent until the Auth0 Angular SDK has finished loading.

Start with importing the SharedModule into the AppModule:

import { provideHttpClient } from '@angular/common/http';

import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';

import { AuthModule } from '@auth0/auth0-angular';

import { environment as env } from '../environments/environment';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { SharedModule } from './shared';

@NgModule({

declarations: [AppComponent],

imports: [

BrowserModule,

AppRoutingModule,

AuthModule.forRoot({

  ...env.auth0,

}),

SharedModule

],

providers: [provideHttpClient()],

bootstrap: [AppComponent],

})

export class AppModule {}

Next, open src/app/app.component.ts and assign Auth0's isLoading$ observable to a variable:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-root',

templateUrl: './app.component.html',

})

export class AppComponent {

private auth = inject(AuthService);

isAuth0Loading$ = this.auth.isLoading$;

}

Open src/app/app.component.html and update it as follows:

<ng-template #auth0Loaded>

While the SDK is loading, the PageLoaderComponent renders, which shows up an animation. Log out and log back in to see this in action. No more UI flashing should happen.

Render navigation tabs conditionally

There may be use cases where you want to hide user interface elements from users who have not logged in to your application. For this starter application, only authenticated users should see the navigation tabs to access the /protected and /admin pages.

To implement this use case, you'll rely once again on the isAuthenticated$ Observable from the AuthService.

Open the src/app/shared/components/navigation/desktop/nav-bar-tabs.component.ts component file that defines your desktop navigation tabs and update it like so:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-nav-bar-tabs',

templateUrl: './nav-bar-tabs.component.html',

})

export class NavBarTabsComponent {

private auth = inject(AuthService);

isAuthenticated$ = this.auth.isAuthenticated$;

}

Open the src/app/shared/components/navigation/desktop/nav-bar-tabs.component.html component file and update it as follows:

<ng-container *ngIf="isAuthenticated$ | async">

<app-nav-bar-tab path="/protected" label="Protected"></app-nav-bar-tab>

<app-nav-bar-tab path="/admin" label="Admin"></app-nav-bar-tab>

Next, open the src/app/shared/components/navigation/mobile/mobile-nav-bar-tabs.component.ts component file that defines your mobile navigation tabs and update it like so:

import { Component, EventEmitter, inject, Output } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

@Component({

selector: 'app-mobile-nav-bar-tabs',

templateUrl: './mobile-nav-bar-tabs.component.html',

})

export class MobileNavBarTabsComponent {

@Output() mobileNavBarTabClick = new EventEmitter();

private auth = inject(AuthService);

isAuthenticated$ = this.auth.isAuthenticated$;

onMobileNavBarTabClick(path: string): void {

this.mobileNavBarTabClick.emit(path);

}

}

Open the src/app/shared/components/navigation/mobile/nav-bar-tabs.component.html component file and update it as follows:

<app-mobile-nav-bar-tab

path="/profile"

label="Profile"

(mobileNavBarTabClick)="onMobileNavBarTabClick($event)"

<app-mobile-nav-bar-tab

path="/public"

label="Public"

(mobileNavBarTabClick)="onMobileNavBarTabClick($event)"

<ng-container *ngIf="isAuthenticated$ | async">

<app-mobile-nav-bar-tab

  path="/protected"

  label="Protected"

  (mobileNavBarTabClick)="onMobileNavBarTabClick($event)"

></app-mobile-nav-bar-tab>

<app-mobile-nav-bar-tab

  path="/admin"

  label="Admin"

  (mobileNavBarTabClick)="onMobileNavBarTabClick($event)"

></app-mobile-nav-bar-tab>

Log out from your Angular application and notice how now you can only see the tabs for the /profile and /public pages in the navigation bar, along with the login and sign-up buttons. Log in and then see the rest of the navigation bar show up.

Keep in mind that this does not restrict access to the /admin and /protected pages at all. You'll learn how to use the Auth0 Angular SDK to protect Angular routes in the next section.

Add Route Guards to Angular

You can create an authentication route guard to protect Angular routes. Angular will ask users who visit the route to log in if they haven't already. Once they log in, Angular takes them to the route they tried to access.

You can apply a guard to any route defined in the Angular router module by updating src/app/app-routing.module.ts as follows:

import { NgModule } from '@angular/core';

import { RouterModule, Routes } from '@angular/router';

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

const routes: Routes = [

{

path: '',

pathMatch: 'full',

loadChildren: () =>

  import('./features/home/home.module').then((m) => m.HomeModule),

},

{

path: 'profile',

loadChildren: () =>

  import('./features/profile/profile.module').then((m) => m.ProfileModule),

canActivate: [AuthGuard],

},

{

path: 'public',

loadChildren: () =>

  import('./features/public/public.module').then((m) => m.PublicModule),

},

{

path: 'protected',

loadChildren: () =>

  import('./features/protected/protected.module').then(

    (m) => m.ProtectedModule

  ),

canActivate: [AuthGuard],

},

{

path: 'admin',

loadChildren: () =>

  import('./features/admin/admin.module').then((m) => m.AdminModule),

canActivate: [AuthGuard],

},

{

path: 'callback',

loadChildren: () =>

  import('./features/callback/callback.module').then((m) => m.CallbackModule),

},

{

path: '**',

loadChildren: () =>

  import('./features/not-found/not-found.module').then(

    (m) => m.NotFoundModule

  ),

},

];

@NgModule({

imports: [RouterModule.forRoot(routes)],

exports: [RouterModule],

})

export class AppRoutingModule {}

You use the AuthGuard from the Auth0 Angular SDK to protect the /profile, /protected, and /admin routes by adding it as the value of the canActivate route configuration property.

If the conditions defined by AuthGuard pass, the component renders. Otherwise, AuthGuard instructs Angular to take you to the Auth0 Universal Login Page to authenticate.

You can now test that these guarded paths require users to log in before accessing them. Log out and try to access the Profile page, Protected page, or the Admin page. If it works, Angular redirects you to log in with Auth0.

Once you log in, Angular should take you to the /profile page as specified by the appState.target property present in the login button component definition.

Client-side guards improve the user experience of your Angular application, not its security.

In Security StackExchange, Conor Mancone explains that server-side guards are about protecting data while client-side guards are about improving user experience.

The main takeaways from his response are:

Get User Profile Information in Angular

After a user successfully logs in, Auth0 sends an ID token to your Angular application. Authentication systems, such as Auth0, use ID Tokens in token-based authentication to cache user profile information and provide it to a client application. The caching of ID tokens can improve the performance and responsiveness of your Angular application.

You can use the data from the ID token to personalize the user interface of your Angular application. The Auth0 Angular SDK decodes the ID token and stores its data in the user$ Observable exposed via the AuthService. Some of the ID token information includes the name, nickname, picture, and email of the logged-in user.

How can you use the ID token to create a profile page for your users?

Update src/app/features/profile/profile.component.ts as follows:

import { Component, inject } from '@angular/core';

import { AuthService } from '@auth0/auth0-angular';

import { map } from 'rxjs/operators';

@Component({

selector: 'app-profile',

templateUrl: './profile.component.html',

})

export class ProfileComponent {

private auth = inject(AuthService);

title = 'Decoded ID Token';

user$ = this.auth.user$;

code$ = this.user$.pipe(map((user) => JSON.stringify(user, null, 2)));

}

Next, update src/app/features/profile/profile.component.html as follows:

<h1 id="page-title" class="content__title">Profile Page</h1>

<div class="content__body">

  <p id="page-description">

    <span>

      You can use the <strong>ID Token</strong> to get the profile

      information of an authenticated user.

    </span>

    <span>

      <strong>Only authenticated users can access this page.</strong>

    </span>

  </p>

  <ng-container *ngIf="user$ | async as user">

    <div class="profile-grid">

      <div class="profile__header">

        <img [src]="user.picture" alt="Profile" class="profile__avatar" />

        <div class="profile__headline">

          <h2 class="profile__title">{{ user.name }}</h2>

          <span class="profile__description">{{ user.email }}</span>

        </div>

      </div>

      <ng-container *ngIf="code$ | async as code">

        <div class="profile__details">

          <app-code-snippet

            [title]="title"

            [code]="code"

          ></app-code-snippet>

        </div>

      </ng-container>

    </div>

  </ng-container>

</div>

What's happening within the ProfileComponent?

The ProfileComponent renders user information that you could consider private or sensitive. Additionally, the user property is null if there is no logged-in user. So either way, this component should only render if Auth0 has authenticated the user. You are already restricting access to this page component by using the authGuard in the /profile route definition of your Angular router module, src/app/app-routing.module.ts.

If you are logged in to your application, visit http://localhost:4040/profile to see your user profile details.

Authentication Beyond Passwords: Try Passkeys Today

So far, you have seen how a user can sign up or log in to your application with a username and password. However, you can free your users from having to remember yet another password by allowing them to use passkeys as a new way to log in.

Passkeys are a phishing-resistant alternative to traditional authentication factors, such as the username/password combo, that offer an easier and more secure login experience to users.

You don't have to write any new code to start using passkeys in your application. You can follow the "Authentication with Passkeys" lab to learn how to enable passkeys in your Auth0 tenant and learn more about this emerging technology. Once you complete that optional lab, you can come back to this guide to continue learning about how to access protected API resources on behalf of a user from your application.

A form modal giving you information on how a passkey works and the option to create a passkey

Integrate Angular with an API Server

This section focuses on showing you how to get an access token in your Angular application and how to use it to make API calls to protected API endpoints.

When you use Auth0, you delegate the authentication process to a centralized service. Auth0 provides you with functionality to log in and log out users from your Angular application. However, your application may need to access protected resources from an API.

You can also protect an API with Auth0. There are multiple API quickstarts to help you integrate Auth0 with your backend platform.

When you use Auth0 to protect your API, you also delegate the authorization process to a centralized service that ensures only approved client applications can access protected resources on behalf of a user.

How can you make secure API calls from Angular?

Your Angular application authenticates the user and receives an access token from Auth0. The application can then pass that access token to your API as a credential. In turn, your API can use Auth0 libraries to verify the access token it receives from the calling application and issue a response with the desired data.

Instead of creating an API from scratch to test the authentication and authorization flow between the client and the server, you can pair this client application with an API server that matches the technology stack you use at work. The Angular "Hello World" client application that you have been building up can interact with any of the "Hello World" API server samples from the Auth0 Developer Hub.

The "Hello World" API server samples run on http://localhost:6060 by default, which is the same origin URL and port where the mocked JSON server is running. As such, before you set up the "Hello World" API server, locate the tab where you are running the npm run api command and stop the mocked JSON server.

Pick an API code sample in your preferred backend framework and language from the list below and follow the instructions on the code sample page to set it up. Once you complete the sample API server setup, please return to this page to learn how to integrate that API server with your Angular application.

Call a Protected API from Angular

Once you have set up the API server code sample, you should have created an Auth0 Audience value. Store that value in the following field so that you can use it throughout the instructions presented on this page easily:

Auth0 Audience

Now, update the .env file under the Angular project directory as follows:

API_SERVER_URL=http://localhost:6060

AUTH0_DOMAIN=AUTH0-DOMAIN

AUTH0_CLIENT_ID=AUTH0-CLIENT-ID

AUTH0_CALLBACK_URL=http://localhost:4040/callback

AUTH0_AUDIENCE=AUTH0-AUDIENCE

You are using AUTH0_AUDIENCE to add the value of your Auth0 API Audience so that your Angular client application can request resources from the API that such audience value represents.

Let's understand better what the AUTH0_AUDIENCE and API_SERVER_URL values represent.

The API_SERVER_URL is simply the URL where your sample API server listens for requests. In production, you'll change this value to the URL of your live server.

Your Angular application must pass an access token when it calls a target API to access protected resources. You can request an access token in a format that the API can verify by passing the audience to the Auth0 Angular SDK.

The value of the Auth0 Audience must be the same for both the Angular client application and the API server you decided to set up.

Why is the Auth0 Audience value the same for both apps? Auth0 uses the value of the audience prop to determine which resource server (API) the user is authorizing your Angular application to access. It's like a phone number. You want to ensure that your Angular application "texts the right API".

As such, update the set-env.ts script file to integrate these new Auth0 environment variables from .env into your Angular src/environments/environment.ts file:

const { writeFile, existsSync, mkdirSync } = require('fs');

const { promisify } = require('util');

const path = require('path');

const dotenv = require('dotenv');

dotenv.config();

const writeFilePromisified = promisify(writeFile);

const targetPath = './src/environments/environment.ts';

const envConfigFile = `export const environment = {

production: false,

auth0: {

domain: '${process.env['AUTH0_DOMAIN']}',

clientId: '${process.env['AUTH0_CLIENT_ID']}',

authorizationParams: {

  audience: '${process.env['AUTH0_AUDIENCE']}',

  redirect_uri: '${process.env['AUTH0_CALLBACK_URL']}',

},

errorPath: '/callback',

},

api: {

serverUrl: '${process.env['API_SERVER_URL']}',

},

};

`;

(async () => {

try {

await ensureDirectoryExistence(targetPath);

await writeFilePromisified(targetPath, envConfigFile);

} catch (err) {

console.error(err);

throw err;

}

})();

function ensureDirectoryExistence(filePath: string) {

var dirname = path.dirname(filePath);

if (existsSync(dirname)) {

return;

}

ensureDirectoryExistence(dirname);

mkdirSync(dirname);

return;

}

Restart your Angular development server to re-generate the src/environments/environment.ts file:

You are now including an audience property in the authorizationParams configuration object you pass to the AuthModule.forRoot() method. Recall that the AuthModule method initializes the authentication module system.

What about using scopes?

A property that you are not configuring directly in the AuthModule.forRoot() method is the scope property. When you don't pass a scope option to Auth0 Angular SDK, which powers Auth0Plugin, the SDK defaults to using the OpenID Connect Scopes: openid profile email.

The details of the OpenID Connect Scopes go into the ID Token. However, you can define custom API scopes to implement access control. You'll identify those custom scopes in the calls that your client applications make to that API. Auth0 includes API scopes in the access token as the scope claim value.

The Auth0 Angular SDK provides an HttpInjector that automatically attaches access tokens to outgoing requests when using the built-in Angular HttpClient module. However, you must configure the injector to know to which requests it needs to attach access tokens.

Update the configuration of the AuthModule present in the imports array of AppModule and add the AuthHttpInterceptor to the providers array as follows:

import { NgModule } from '@angular/core';

import { provideHttpClient, withInterceptors } from '@angular/common/http';

import { BrowserModule } from '@angular/platform-browser';

import {

AuthHttpInterceptor,

AuthModule,

authHttpInterceptorFn,

} from '@auth0/auth0-angular';

import { environment as env } from '../environments/environment';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';

import { SharedModule } from './shared';

@NgModule({

declarations: [AppComponent],

imports: [

BrowserModule,

AppRoutingModule,

SharedModule,

AuthModule.forRoot({

  ...env.auth0,

  httpInterceptor: {

    allowedList: [

      `${env.api.serverUrl}/api/messages/admin`,

      `${env.api.serverUrl}/api/messages/protected`,

    ],

  },

}),

],

providers: [

AuthHttpInterceptor,

provideHttpClient(withInterceptors([authHttpInterceptorFn])),

],

bootstrap: [AppComponent],

})

export class AppModule {}

Let's break down what is happening in the above code:

First, you are adding AuthHttpInterceptor from @auth0/auth0-angular to the providers array along with adding Auth0's authHttpInterceptorFn to the list of interceptors for the HttpClient.

providers: [

AuthHttpInterceptor,

provideHttpClient(withInterceptors([authHttpInterceptorFn]))

],

This completes the wiring needed to connect the AuthHttpInterceptor with your Angular application request cycle.

Now, you need to tell the SDK which requests to attach access tokens by configuring AuthModule.forRoot(). Based on that configuration, Angular will match the URL of any request that you make using HttpClient against an allowed list of URLs:

httpInterceptor: {

allowedList: [

`${env.api.serverUrl}/api/messages/admin`,

`${env.api.serverUrl}/api/messages/protected`

],

},

If there's a match, Angular attaches an access token to the request's authorization header. You can use a string or a regular expression for the URL matching. For now, you are allowing Angular to attach an access token to requests it makes to http://localhost:6060/api/messages/protected and http://localhost:6060/api/messages/admin.

That's all it takes to integrate Angular with an external API server that is also secured by Auth0 and to use an access token to consume protected server resources from your Angular client application.

Next Steps

You have implemented user authentication in Angular to identify your users, get user profile information, and control the content that your users can access by protecting routes and API resources.

This guide covered the most common authentication use case for an Angular application: simple login and logout. However, Auth0 is an extensible and flexible identity platform that can help you achieve even more. If you have a more complex use case, check out the Auth0 Architecture Scenarios to learn more about the typical architecture scenarios we have identified when working with customers on implementing Auth0.

Have a complex use case?We’ll ensure your development team is set up for success from day one.Have a complex use case?We’ll ensure your development team is set up for success from day one.Talk With An Expert→

We'll cover advanced authentication patterns and tooling in future guides, such as using a pop-up instead of redirecting users to log in, adding permissions to ID tokens, using metadata to enhance user profiles, and much more.