Authgear
Start BuildingHomePortalCommunity
  • Authgear Overview
  • Get Started
    • Start Building
    • 5-Minute Guide
    • Single-Page App
      • JavaScript (Web)
      • React
      • Angular
      • Vue
    • Native/Mobile App
      • iOS SDK
      • Android SDK
        • Android Kotlin coroutine support
        • Android OKHttp Interceptor Extension (Optional)
      • Flutter SDK
      • React Native SDK
      • Ionic SDK
      • Xamarin SDK
      • Using Authgear without SDK (Client side)
    • Regular Web App
      • Express
      • Next.js
      • Python Flask App
      • Java Spring Boot
      • ASP.NET Core MVC
      • Laravel
      • PHP
    • Backend/API Integration
      • Validate JWT in your application server
      • Forward Authentication to Authgear Resolver Endpoint
    • AI Coding tools
      • Cursor/Windsurf
  • How-To Guides
    • Authenticate
      • Add Passkeys Login
      • Add WhatsApp OTP Login
      • Add Email Magic Link Login
      • Add Biometric Login
      • Add Anonymous Users
      • Add authentication to any web page
      • Enable Two-Factor Authentication (2FA)
      • Reauthentication
      • Passwordless Login for Apple App Store Review
      • Change Forgot/Reset Password settings
      • Adjust Phone Number Validation
      • Set Password Expiry
      • Use the OAuth 2.0 State Parameter
      • Setup local development environment for Cookie-based authentication
      • Use Social/Enterprise Login Providers Without AuthUI
    • Single Sign-on
      • App2App Login
      • Pre-authenticated URLs
      • SSO between Mobile Apps / Websites
      • Force Authgear to Show Login Page
      • Single Sign-On with OIDC
      • Single Sign-On with SAML
        • Use Authgear as SAML Identity Provider for Salesforce
        • Use Authgear as SAML Identity Provider for Dropbox
        • SAML Attribute Mapping
    • Social Login / Enterprise Login Providers
      • Social Login Providers
        • Connect Apps to Apple
        • Connect Apps to Google
        • Connect Apps to Facebook
        • Connect Apps to GitHub
        • Connect Apps to LinkedIn
        • Connect Apps to WeChat
      • Enterprise Login Providers
        • Connect Apps to Azure Active Directory
        • Connect Apps to Microsoft AD FS
        • Connect Apps to Azure AD B2C
      • Force Social/Enterprise Login Providers to Show Login Screen
    • Integrate
      • Add custom fields to a JWT Access Token
      • User Analytics by Google Tag Manager
      • Track User Before and After Signup
      • Custom domain
      • Custom Email Provider
      • Custom SMS Provider
        • Twilio
        • Webhook/Custom Script
      • Integrate Authgear with Firebase
    • Monitor
      • Audit Log For Users Activities
      • Audit Log for Admin API and Portal
      • Analytics
    • User Management
      • Account Deletion
      • Import Users using User Import API
      • Export Users using the User Export API
      • Manage Users Roles and Groups
      • How to Handle Password While Creating Accounts for Users
    • User Profiles
      • What is User Profile
      • Access User Profiles
      • Update User Profiles
      • Profile Custom Attributes
      • Update user profile on sign-up using Hooks
    • Events and Hooks
      • Event List
      • Webhooks
      • JavaScript / TypeScript Hooks
      • Only Allow Signups from Inside the Corporate Network using Hooks
    • Mobile Apps
      • Use SDK to make authorized API calls to backend
      • Force authentication on app launch
      • Customize the Login Pop-up / Disable the login alert box
    • Migration
      • Bulk migration
      • Rolling migration
      • Zero-downtime migration
    • Directly accessing Authgear Endpoint
    • Troubleshoot
      • How to Fix SubtleCrypto: digest() undefined Error in Authgear SDK
      • How to Fix CORS Error
  • Design
    • Built-in UI
      • Branding in Auth UI
      • User Settings
      • Privacy Policy & Terms of Service Links
      • Customer Support Link
      • Custom Text
    • Custom UI
      • Authentication Flow API
      • Implement Authentication Flow API using Express
      • Implement Authentication Flow API using PHP
      • Add Custom Login/Signup UI to Native Apps
      • Manually Link OAuth Provider using Account Management API
      • Implement a custom account recovery UI using Authentication Flow API
    • Languages and Localization
    • Custom Email and SMS Templates
  • Concepts
    • Identity Fundamentals
    • Authgear use cases
    • User, Identity and Authenticator
  • Security
    • Brute-force Protection
    • Bot Protection
    • Non-HTTP scheme redirect URI
    • Password Strength
  • Authgear ONCE
    • What is Authgear ONCE
    • Install Authgear ONCE on a VM
    • Install Authgear ONCE on Vultr
    • Install Authgear ONCE on Amazon Web Services (AWS)
  • Reference
    • APIs
      • Admin API
        • Authentication and Security
        • API Schema
        • Admin API Examples
        • Using global node IDs
        • Retrieving users using Admin API
        • User Management Examples
          • Search for users
          • Update user's standard attributes
          • Update user's picture
          • Generate OTP code
      • Authentication Flow API
      • OAuth 2.0 and OpenID Connect (OIDC)
        • UserInfo
        • Supported Scopes
      • User Import API
      • User Export API
    • Tokens
      • JWT Access Token
      • Refresh Token
    • Glossary
    • Billing FAQ
    • Rate Limits
      • Account Lockout
  • Client App SDKs
    • Javascript SDK Reference
    • iOS SDK Reference
    • Android SDK Reference
    • Flutter SDK Reference
    • Xamarin SDK Reference
  • Deploy on your Cloud
    • Running locally with Docker
    • Deploy with Helm chart
    • Authenticating HTTP request with Nginx
    • Configurations
      • Environment Variables
      • authgear.yaml
      • authgear.secrets.yaml
    • Reference Architecture Diagrams
      • Google Cloud Reference Architecture
      • Azure Reference Architecture
      • AWS Reference Architecture
      • Throughput Scaling Reference
Powered by GitBook
On this page
  • Setup Application in Authgear
  • Create an application in the Portal
  • Configure Authorize Redirect URI
  • Configure Post Logout Redirect URI
  • Step 1: Create a simple Angular project
  • Step 2: Install Authgear SDK to the project
  • Step 3: Implement the User Service
  • Step 4: Implement the Auth Redirect
  • Step 5: Add Routes and Context Provider to the App
  • Step 6: Add a Login button
  • Step 7: Show the user information
  • Step 8: Add a Logout button
  • Step 9: Open User Settings
  • Next steps, Calling an API

Was this helpful?

Edit on GitHub
Export as PDF
  1. Get Started
  2. Single-Page App

Angular

Follow this quickstart tutorial to add authentication to your Angular application

PreviousReactNextVue

Last updated 8 months ago

Was this helpful?

Authgear helps you add user logins to your Angular apps. It provides prebuilt login page and user settings page that accelerate the development.

Follow this 15 minutes tutorial to create a simple app using Angular with Authgear SDK.

Check out and clone .

Table of Content

Setup Application in Authgear

Signup for an account in and create a Project.

After that, we will need to create an Application in the Project Portal.

Create an application in the Portal

  1. Go to Applications on the left menu bar.

  2. Click ⊕Add Application in the top tool bar.

  3. Input the name of your application, e.g. "MyAwesomeApp".

  4. Select Single Page Application as the application type

  5. Click "Save" to create the application

Configure Authorize Redirect URI

The Redirect URI is a URL in you application where the user will be redirected to after login with Authgear. In this path, make a finish authentication call to complete the login process.

For this tutorial, add http://localhost:4000/auth-redirect to Authorize Redirect URIs.

Configure Post Logout Redirect URI

The Post Logout Redirect URI is the URL users will be redirected after they have logged out. The URL must be whitelisted.

For this tutorial, add http://localhost:4000/ to Post Logout Redirect URIs.

Save the configuration before next steps.

Step 1: Create a simple Angular project

Here are some recommended steps to scaffold an Angular project. You can skip this part if you are adding Authgear to an existing project. See Step 2: Install Authgear SDK to the project in the next section.

Install the Angular CLI

To install the Angular CLI, open a terminal window and run the following command:

npm install -g @angular/cli

Create initial workspace

Run the following cli command to create a new workspace and initial app called my-app with a routing module generated.

# Create a workspace called my-app
ng new my-app --routing --defaults
# Move into the project directory
cd my-app

Edit script for launching the app

In the package.json file, edit the start script in the script section

# before
"start": "ng serve"

# after
"start": "ng serve --port 4000"

The start script run the app in development mode on port 4000 instead of the default one.

Edit the app.component.html file

By default, the Angular CLI generated an initial application for us, but for simplicity, we recommend to modify some of these files to scratch.

In the src/app/app.component.html file, remove all the lines and add the following line:

<div>Hello world</div>

Run your initial app

Run npm start now to run the project and you will see "Hello world" on http://localhost:4000.

Step 2: Install Authgear SDK to the project

Run the following command within your Angular project directory to install the Authgear Web SDK

npm install --save-exact @authgear/web

In src/app/app.component.ts , import authgear and call the configure function to initialize an Authgear instance on application loads.

// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import authgear from '@authgear/web';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  // configure Authgear container instance
  initAuthgear(): Promise<void> {
    return authgear.configure({
      endpoint: '<your_app_endpoint>',
      clientID: '<your_client_id>',
      sessionType: 'refresh_token',
    });
  }

  ngOnInit(): void {
    this.initAuthgear().catch((e) => {
      // Error handling
      console.log(e);
    });
  }
}

The Authgear container instance takes endpoint and clientID as parameters. They can be obtained from the application page created in Setup Application in Authgear.

It is recommend to render the app after configure() resolves. So by the time the app is rendered, Authgear is ready to use.

Run npm start now and you should see a page with "Hello World" and no error message in the console if Authgear SDK is configured successfully

Step 3: Implement the User Service

Since we want to reference the logged in state in anywhere of the app, let's put the state in a service with user.service.ts in the /src/app/services/ folder.

In user.service.ts, it will have a isLoggedIn boolean variable. The isLoggedIn boolean variable can be auto updated using the onSessionStateChange callback. This callback can be stored in delegate which is in the local SDK container.

// src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import authgear from '@authgear/web';

@Injectable({
  providedIn: 'root',
})
export class UserService {
  // By default the user is not logged in
  isLoggedIn: boolean = false;

  constructor() {
    // When the sessionState changed, logged in state will also be changed
    authgear.delegate = {
      onSessionStateChange: (container) => {
        // sessionState is now up to date
        // value of sessionState can be "NO_SESSION" or "AUTHENTICATED"
        const sessionState = container.sessionState;
        if (sessionState === 'AUTHENTICATED') {
          this.isLoggedIn = true;
        } else {
          this.isLoggedIn = false;
        }
      },
    };
  }
}

Step 4: Implement the Auth Redirect

Next, we will add an "auth-redirect" page for handling the authentication result after the user have been authenticated by Authgear.

Create the auth-redirect component using the following command:

ng generate component auth-redirect

We will inject the router and the UserService to get the use of navigation and the isLoggedIn state.

Call the Authgear finishAuthentication() function in the Auth Redirect component to send a token back to Authgear server in exchange for access token and refresh token. Don't worry about the technical jargons, finishAuthentication() will do all the hard work for you and and save the authentication data.

When the authentication is finished, the isLoggedIn state from the UserService will automatic set to true. Finally, navigate back to root (/) which is our Home page.

The final auth-redirect.component.ts will look like this

// src/app/auth-redirect/auth-redirect.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import authgear from '@authgear/web';
import { Router } from '@angular/router';

@Component({
  selector: 'app-auth-redirect',
  templateUrl: './auth-redirect.component.html',
  styleUrls: ['./auth-redirect.component.css'],
})
export class AuthRedirectComponent implements OnInit {
  constructor(private router: Router, private user: UserService) {}

  ngOnInit(): void {
    authgear
      .finishAuthentication()
      .catch((e) => console.error(e))
      .then(() => {
        this.router.navigate(['']);
      });
  }
}

Step 5: Add Routes and Context Provider to the App

Next, we will add a "Home" page . Create a home component using the following command:

ng generate component home

Then import HomeComponent and AuthRedirectComponent as routes. We can add those routes in the app-routing.module.ts file:

// src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthRedirectComponent } from './auth-redirect/auth-redirect.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'auth-redirect', component: AuthRedirectComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

You can apply those routes in src/app/app.component.html by replace the lines with the following:

<router-outlet></router-outlet>

The file structure should now look like

src
├── (...)
└── app
    ├── app-routing.module.ts
    ├── app.component.ts
    ├── app.component.html
    ├── app.module.ts
    ├── (...)
    ├── auth-redirect
    │   ├── auth-redirect.component.ts
    │   ├── auth-redirect.component.html
    │   └── (...)
    ├── home
    │   ├── home.component.ts
    │   ├── home.component.html
    │   └── (...)
    └── services
        └── user.service.ts

Step 6: Add a Login button

First we will import the Authgear dependency and inject the UserService in home.component.ts. Then add the startLogin method which will call startAuthentication(ConfigureOptions). This will redirect the user to the login page.

// src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import authgear from '@authgear/web';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  constructor(public user: UserService) {}

  ngOnInit(): void {}

  startLogin(): void {
    authgear
      .startAuthentication({
        redirectURI: 'http://localhost:4000/auth-redirect',
        prompt: 'login',
      })
      .then(
        () => {
          // started authorization, user should be redirected to Authgear
        },
        (err) => {
          // failed to start authorization
          console.error(err);
        }
      );
  }
}

Then you can add a button which will trigger the startLogin method in home.component.html:

<h1>Home Page</h1>
<button type="button" (click)="startLogin()">Login</button>

You can now run npm start and you will be redirected to the Authgear Login page when you click the Login button.

Step 7: Show the user information

The Authgear SDK helps you get the information of the logged in users easily.

In the last step, the user is successfully logged in so let's try to print the user ID (sub) of the user in the Home page.

In home component, we will add a simple Loading splash and a greeting message printing the Sub ID. We will add two conditional elements such that they are only shown when user is logged in. We can also change the login button to show only if the user is not logged in.

Make use of isLoggedIn from the UserService to control the components on the page. Fetch the user info by fetchInfo() and access its sub property.

// src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import authgear from '@authgear/web';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  isLoading: boolean = false;
  greetingMessage: string = '';

  constructor(public user: UserService) {}

  async updateGreetingMessage() {
    this.isLoading = true;
    try {
      if (this.user.isLoggedIn) {
        const userInfo = await authgear.fetchUserInfo();
        this.greetingMessage = 'The current User sub: ' + userInfo.sub;
      }
    } finally {
      this.isLoading = false;
    }
  }

  ngOnInit(): void {
    this.updateGreetingMessage().catch((e) => {
      console.error(e);
    });
  }

  startLogin(): void {
    authgear
      .startAuthentication({
        redirectURI: 'http://localhost:4000/auth-redirect',
        prompt: 'login',
      })
      .then(
        () => {
          // started authorization, user should be redirected to Authgear
        },
        (err) => {
          // failed to start authorization
          console.error(err);
        }
      );
  }
}

In the home.component.html:

<h1>Home Page</h1>
<span *ngIf="isLoading">Loading</span>
<span *ngIf="greetingMessage">{{ greetingMessage }}</span>
<div *ngIf="!user.isLoggedIn">
  <button type="button" (click)="startLogin()">Login</button>
</div>

Run the app again, the User ID (sub) of the user should be printed on the Home page.

Step 8: Add a Logout button

Finally, let's add an Logout button when user is logged in.

In home.component.html, we will add a conditional element in the markup:

<div *ngIf="user.isLoggedIn">
  <button type="button" (click)="logout()">Logout</button>
</div>

And add the logout method:

logout(): void {
  authgear
    .logout({
      redirectURI: 'http://localhost:4000/',
    })
    .then(
      () => {
        this.greetingMessage = '';
      },
      (err) => {
        console.error(err);
      }
    );
}

Run the app again, we can now logout by clicking the logout button.

Step 9: Open User Settings

Authgear provide a built-in UI for the users to set their attributes and change security settings.

Use the open function to open the setting page at <your_app_endpoint>/settings

In home.component.html append a conditional link to the logout button section.

<div *ngIf="user.isLoggedIn">
  <button type="button" (click)="logout()">Logout</button>
  <br />
  <a target="_blank" rel="noreferrer" (click)="userSetting($event)" href="#">
    User Setting
  </a>
</div>

And add the userSetting method:

import authgear, { Page } from "@authgear/web";

async userSetting(event: MouseEvent) {
  event.preventDefault();
  event.stopPropagation();
  await authgear.open(Page.Settings);
}

This the resulting home.component.ts:

// src/app/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService } from '../services/user.service';
import authgear, { Page } from '@authgear/web';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  isLoading: boolean = false;
  greetingMessage: string = '';

  constructor(public user: UserService) {}

  async updateGreetingMessage() {
    this.isLoading = true;
    try {
      if (this.user.isLoggedIn) {
        const userInfo = await authgear.fetchUserInfo();
        this.greetingMessage = 'The current User sub: ' + userInfo.sub;
      }
    } finally {
      this.isLoading = false;
    }
  }

  ngOnInit(): void {
    this.updateGreetingMessage().catch((e) => {
      console.error(e);
    });
  }

  startLogin(): void {
    authgear
      .startAuthentication({
        redirectURI: 'http://localhost:4000/auth-redirect',
        prompt: 'login',
      })
      .then(
        () => {
          // started authorization, user should be redirected to Authgear
        },
        (err) => {
          // failed to start authorization
          console.error(err);
        }
      );
  }

  logout(): void {
    authgear
      .logout({
        redirectURI: 'http://localhost:4000/',
      })
      .then(
        () => {
          this.greetingMessage = '';
        },
        (err) => {
          console.error(err);
        }
      );
  }

  async userSetting(event: MouseEvent) {
    event.preventDefault();
    event.stopPropagation();
    await authgear.open(Page.Settings);
  }
}

This is the resulting home.component.html:

<h1>Home Page</h1>
<span *ngIf="isLoading">Loading</span>
<span *ngIf="greetingMessage">{{ greetingMessage }}</span>
<div *ngIf="!user.isLoggedIn">
  <button type="button" (click)="startLogin()">Login</button>
</div>
<div *ngIf="user.isLoggedIn">
  <button type="button" (click)="logout()">Logout</button>
  <br />
  <a target="_blank" rel="noreferrer" (click)="userSetting($event)" href="#">
    User Setting
  </a>
</div>

Next steps, Calling an API

To access restricted resources on your backend application server, the HTTP requests should include the access token in their Authorization headers. The Web SDK provides a fetch function which automatically handle this, or you can get the token with authgear.accessToken.

Option 1: Using fetch function provided by Authgear SDK

authgear
    .fetch("YOUR_SERVER_URL")
    .then(response => response.json())
    .then(data => console.log(data));

Option 2: Add the access token to the HTTP request header

You can get the access token through authgear.accessToken. Call refreshAccessTokenIfNeeded every time before using the access token, the function will check and make the network call only if the access token has expired. Include the access token into the Authorization header of the application request.

authgear
    .refreshAccessTokenIfNeeded()
    .then(() => {
        // access token is ready to use
        // accessToken can be string or undefined
        // it will be empty if user is not logged in or session is invalid
        const accessToken = authgear.accessToken;

        // include Authorization header in your application request
        const headers = {
            Authorization: `Bearer ${accessToken}`
        };
    });

For Windows clients, please find your reference in for more information on installing the Angular CLI.

Authgear SDK provides the fetch function for you to call your application server. This fetch function will include the Authorization header in your application request, and handle refresh access token automatically. The authgear.fetch implements .

https://angular.io/guide/setup-local
fetch
🕐
the Sample Project on GitHub
https://portal.authgear.com/
Setup Application in Authgear
Create a simple Angular project
Install Authgear SDK to the project
Implement User Service
Implement the Auth Redirect page
Add a Login button
Show the user information
Add a Logout button
Open User Settings
Calling an API
Configure Authorized Redirect URIs and Post Logout Redirect URIs.
User will be redirected to the Authgear login page by clicking the login button
Show the User ID, a link to User Settings and a logout button after login