angular logo
typescript logo

Angular Authentication By Example

v14
Published on November 15, 2022

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:

  • How to add user login, sign-up, and logout to Angular Applications.
  • How to create route guards to protect Angular application routes.
  • How to make API calls from Angular to request data from a protected API.
  • How to get user profile information to personalize an Angular user interface.

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:

COMMAND
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:

COMMAND
cd spa_angular_typescript_hello-world

Install the Angular project dependencies as follows:

COMMAND
npm install

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:

COMMAND
touch .env

Populate .env with the following environment variables:

.env
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:

set-env.ts
const { writeFile } = require('fs');
const { promisify } = require('util');
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 writeFilePromisified(targetPath, envConfigFile);
} catch (err) {
console.error(err);
throw err;
}
})();

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:

COMMAND
npm start

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

COMMAND
npm run 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

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:

Name
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:

Allowed Callback URLs
http://localhost:4040/callback

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

Allowed Logout URLs
http://localhost:4040

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

Allowed Web Origins
http://localhost:4040

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.

You can also use custom domains to allow Auth0 to do the authentication heavy lifting for you without compromising your branding experience.

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:

For security, these configuration values are stored in memory and only used locally. They are gone as soon as you refresh the page! As an extra precaution, you should use values from an Auth0 test application instead of a production one.

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:

.env
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:

set-env.ts
const { writeFile } = require('fs');
const { promisify } = require('util');
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']}',
redirectUri: '${process.env['AUTH0_CALLBACK_URL']}',
},
api: {
serverUrl: '${process.env['API_SERVER_URL']}',
},
};
`;
(async () => {
try {
await writeFilePromisified(targetPath, envConfigFile);
} catch (err) {
console.error(err);
throw err;
}
})();

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

COMMAND
npm start

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.

You'll be using Angular CLI to generate and modify files. You can install it using npm by following the instructions in their official docs.

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

COMMAND
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:

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

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

src/app/features/callback/callback.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '@app/shared';
import { CallbackComponent } from './callback.component';
@NgModule({
declarations: [CallbackComponent],
imports: [CommonModule, SharedModule],
})
export class CallbackModule {}

Update the CallbackRoutingModule to set CallbackComponent as the default route:

src/app/features/callback/callback-routing.module.ts
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:

src/app/features/callback/callback.component.html
<div class="page-layout">
<app-nav-bar></app-nav-bar>
<app-mobile-nav-bar></app-mobile-nav-bar>
<div class="page-layout__content">
<ng-content></ng-content>
</div>
</div>

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:

src/app/app-routing.module.ts
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:

  • Your users won't see any flashing of the home page component, which renders at the root path, /.
  • By showing the navigation bar in the /callback route, your user may feel that your Angular application loads fast.
  • By not showing the footer, your users may feel that your Angular application loads smoothly.
  • You can avoid making unnecessary or costly API calls that may run when loading your home page components.

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:

  • This Angular application offers a /profile page that will display user profile information such as name and email address. However, this application also lazy loads that /profile route using the Angular Router.
  • Since user profile information is private, it must be protected against unauthorized access.
  • The Auth0 Angular SDK allows you to easily require users to log in before they can access a route.
  • When a user who is not logged in clicks on the /profile page navigation tab, Auth0 will redirect them to a page to log in.
  • Once your users log in, Auth0 will redirect them to your Angular application with some metadata that allows your application to redirect them to the protected page they intended to access.
  • When you use http://localhost:4040 as the Auth0 Callback URL, Auth0 will redirect your users to the home page first. Depending on how fast your application renders pages and handles redirects, your users may see the home page first before Angular takes them to the /profile page when the connection is slow or when you are lazy loading that route. This quick re-routing makes your user interface "flash", which makes the user interface feel janky or glitchy.
  • However, when you use http://localhost:4040/callback as the Auth0 Callback URL, Auth0 will take your users to a /callback route after they log in. You can then display a loading animation or nothing at all in that special route. Doing so makes the transition from /callback to /profile smoother as no unrelated or unexpected content shows up in the process.

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:

COMMAND
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:

src/app/app.module.ts
import { HttpClientModule } 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,
HttpClientModule,
AuthModule.forRoot({
...env.auth0,
}),
],
bootstrap: [AppComponent],
})
export class AppModule {}

You use the forRoot() pattern to configure AuthModule, which takes an object with the domain and clientId 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.

Add User Login to Angular

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:

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

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

src/app/shared/components/buttons/login-button.component.ts
import { Component } 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 {
constructor(private auth: 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

You can make users land directly on a sign-up page instead of a login page by specifying the screen_hint=signup property in the configuration object of loginWithRedirect():

{
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:

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

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

src/app/shared/components/buttons/signup-button.component.ts
import { Component } 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 {
constructor(private auth: AuthService) {}
handleSignUp(): void {
this.auth.loginWithRedirect({
appState: {
target: '/profile',
},
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:

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

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

src/app/shared/components/buttons/logout-button.component.ts
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { AuthService } from '@auth0/auth0-angular';
@Component({
selector: 'app-logout-button',
template: `
<button class="button__logout" (click)="handleLogout()">Log Out</button>
`,
})
export class LogoutButtonComponent {
constructor(
private auth: AuthService,
@Inject(DOCUMENT) private doc: Document,
) {}
handleLogout(): void {
this.auth.logout({ 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 methods, you can pass an object argument to logout() to define parameters for the /v2/logout call. This process is fairly invisible to the user. See LogoutOptions for more details on the configuration options available.

Here, you pass the 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 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 when the user is logged in.

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

src/app/shared/components/navigation/desktop/nav-bar-buttons.component.ts
import { Component } from '@angular/core';
import { AuthService } from "@auth0/auth0-angular";
@Component({
selector: 'app-nav-bar-buttons',
templateUrl: './nav-bar-buttons.component.html',
})
export class NavBarButtonsComponent {
isAuthenticated$ = this.authService.isAuthenticated$
constructor(private authService: AuthService) {}
}

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:

src/app/shared/components/navigation/desktop/nav-bar-buttons.component.html
<div class="nav-bar__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>
</div>

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:

src/app/shared/components/navigation/mobile/mobile-nav-bar-buttons.component.ts
import { Component } 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 {
isAuthenticated$ = this.authService.isAuthenticated$
constructor(private authService: AuthService) {}
}

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:

src/app/shared/components/navigation/mobile/mobile-nav-bar-buttons.component.html
<div class="mobile-nav-bar__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>
</div>

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
You can customize the appearance of New Universal Login pages. You can also override any text in the New Experience using the Text Customization API.

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:

src/app/app.module.ts
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { SharedModule } from './shared';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, AppRoutingModule, HttpClientModule, SharedModule],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}

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

src/app/app.component.ts
import { Component } from '@angular/core';
import { AuthService } from "@auth0/auth0-angular";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
isAuth0Loading$ = this.authService.isLoading$;
constructor(private authService: AuthService) {}
}

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

src/app.component.html
<div class="page-layout" *ngIf="isAuth0Loading$ | async; else auth0Loaded">
<app-page-loader></app-page-loader>
</div>
<ng-template #auth0Loaded>
<router-outlet></router-outlet>
</ng-template>

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:

src/app/shared/components/navigation/desktop/nav-bar-tabs.component.ts
import { Component } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
@Component({
selector: 'app-nav-bar-tabs',
templateUrl: './nav-bar-tabs.component.html',
})
export class NavBarTabsComponent {
isAuthenticated$ = this.authService.isAuthenticated$;
constructor(private authService: AuthService) {}
}

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

src/app/sharedcomponents/navigation/desktop/nav-bar-tabs.component.html
<div class="nav-bar__tabs">
<app-nav-bar-tab path="/profile" label="Profile"></app-nav-bar-tab>
<app-nav-bar-tab path="/public" label="Public"></app-nav-bar-tab>
<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>
</ng-container>
</div>

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:

src/app/sharedcomponents/navigation/mobile/mobile-nav-bar-tabs.component.ts
import { Component, EventEmitter, 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<string>();
isAuthenticated$ = this.auth.isAuthenticated$;
constructor(private auth: AuthService) {}
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:

src/app/shared/components/navigation/mobile/mobile-nav-bar-tabs.component.html
<div class="mobile-nav-bar__tabs">
<app-mobile-nav-bar-tab
path="/profile"
label="Profile"
(mobileNavBarTabClick)="onMobileNavBarTabClick($event)"
></app-mobile-nav-bar-tab>
<app-mobile-nav-bar-tab
path="/public"
label="Public"
(mobileNavBarTabClick)="onMobileNavBarTabClick($event)"
></app-mobile-nav-bar-tab>
<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>
</ng-container>
</div>

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:

src/app/app-routing.module.ts
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:

  • You can't rely on client-side restrictions, such as navigation guards and protected routes, to protect sensitive information.
    • Attackers can potentially get around client-side restrictions.
  • Your server should not return any data that a user should not access. The wrong approach is to return all the user data from the server and let the front-end framework decide what to display and what to hide based on the user authentication status.
    • Anyone can open the browser's developer tools and inspect the network requests to view all the data.
  • The use of navigation guards helps improve user experience, not user security.
    • Without guards, a user who has not logged in may wander into a page with restricted information and see an error like "Access Denied".
    • With guards that match the server permissions, you can prevent users from seeing errors by preventing them from visiting the restricted page.

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:

src/app/features/profile/profile.component.ts
import { Component } 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 {
title = 'Decoded ID Token';
user$ = this.authService.user$;
code$ = this.user$.pipe(map((user) => JSON.stringify(user, null, 2)));
constructor(private authService: AuthService) {}
}

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

src/app/features/profile/profile.component.html
<app-page-layout>
<div class="content-layout">
<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>
</div>
</app-page-layout>

What's happening within the ProfileComponent?

  • You display three properties from the user object in the user interface: name, picture, and email.

  • Since the data comes from an Observable, you can subscribe to it directly in the template via the async pipe.

  • Finally, you display the full content of the decoded ID token within a code box. You can now see all the other properties available for you to use. The properties are known as "token claims".

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.

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.

actix-web
rust
Actix Web/Rust API:Authorization Code Sample
Code sample of a simple Actix Web server that implements token-based authorization using Auth0.
aspnet-core
csharp
ASP.NET Core Code Sample:Web API Authorization
Code sample of a simple ASP.NET Core server that implements token-based authorization using Auth0.
django
python
Django/Python API:Authorization Code Sample
Code sample of a simple Django server that implements token-based authorization using Auth0.
express
javascript
Express.js Code Sample:Basic API Authorization
Code sample of a simple Express.js server that implements token-based authorization using Auth0.
express
typescript
Express.js/TypeScript Code Sample:Basic API Authorization
Code sample of a simple Express.js server built with TypeScript that implements token-based authorization using Auth0.
flask
python
Flask/Python API:Authorization Code Sample
Code sample of a simple Flask server that implements token-based authorization using Auth0.
laravel
php
Laravel/PHP API:Authorization Code Sample
Code sample of a simple Laravel server that implements token-based authorization using Auth0.
lumen
php
Lumen/PHP API:Authorization Code Sample
Code sample of a simple Lumen server that implements token-based authorization using Auth0.
phoenix
elixir
Phoenix/Elixir API:Authorization Code Sample
Code sample of a simple Phoenix server that implements token-based authorization using Auth0.
rails
ruby
Ruby on Rails API:Authorization Code Sample
Code sample of a simple Rails server that implements authorization using Auth0.
spring
java
Spring Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, using Spring Security.
spring
java
Spring Functional Code Sample:Basic API Authorization
Java code sample that implements token-based authorization in a Spring Web API server to protect API endpoints, following a functional approach.
standard-library
golang
Golang Code Sample:Basic API Authorization
Code sample of a simple Golang server that implements token-based authorization using Auth0.

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:

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

.env
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".

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

set-env.ts
const { writeFile } = require('fs');
const { promisify } = require('util');
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']}',
redirectUri: '${process.env['AUTH0_CALLBACK_URL']}',
audience: '${process.env['AUTH0_AUDIENCE']}',
},
api: {
serverUrl: '${process.env['API_SERVER_URL']}',
},
};
`;
(async () => {
try {
await writeFilePromisified(targetPath, envConfigFile);
} catch (err) {
console.error(err);
throw err;
}
})();

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

COMMAND
npm start

You are now including an audience property in the configuration object you pass to the AuthModule.forRoot() method.

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.

  • openid: This scope informs the Auth0 Authorization Server that the Client is making an OpenID Connect (OIDC) request to verify the user's identity. OpenID Connect is an authentication protocol.

  • profile: This scope value requests access to the user's default profile information, such as name, nickname, and picture.

  • email: This scope value requests access to the email and email_verified information.

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 concepts about API scopes or permissions are better covered in an Auth0 API tutorial such as "Use TypeScript to Create a Secure API with Node.js and Express: Role-Based Access Control".

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:

src/app/app.module.ts
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { AuthHttpInterceptor, 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/shared.module';
import { CallbackModule } from './features/callback/callback.module';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
AppRoutingModule,
SharedModule,
HttpClientModule,
CallbackModule,
AuthModule.forRoot({
...env.auth0,
httpInterceptor: {
allowedList: [`${env.api.serverUrl}/api/messages/admin`, `${env.api.serverUrl}/api/messages/protected`],
},
}),
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthHttpInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}

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

First, you are importing AuthHttpInterceptor from @auth0/auth0-angular along with HTTP_INTERCEPTORS from @angular/common/http. HTTP_INTERCEPTORS is a multi-provider token that represents the array of registered HttpInterceptor objects.

Next, you are adding the providers property to the configuration object of AppModule as follows to register the AuthHttpInterceptor injector as a provider:

providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthHttpInterceptor,
multi: true,
},
],

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.

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.