# FusionAuth QuickStart for Angular QuickStart integration of an Angular web application with FusionAuth. > For the index of this section of the site, see [llms.txt](https://4002.18-224-161-104.sslip.io/docs/llms.txt) ![Angular](https://4002.18-224-161-104.sslip.io/img/icons/angular-spa.svg) In this QuickStart, you are going to build an application with Angular and integrate it with FusionAuth. You'll be building it for [ChangeBank](https://www.youtube.com/watch?v=CXDxNCzUspM), a global leader in converting dollars into coins. It'll have areas reserved for users who have logged in as well as public facing sections. The Docker Compose file and source code for a complete application are available at [https://github.com/FusionAuth/fusionauth-quickstart-javascript-angular-web](https://github.com/FusionAuth/fusionauth-quickstart-javascript-angular-web). ## Prerequisites * [Node v18](https://nodejs.org/en): This will be used to run the Angular application. * [Docker](https://www.docker.com): The quickest way to stand up FusionAuth. (There are [other ways](https://4002.18-224-161-104.sslip.io/docs/get-started/download-and-install.md)). This app has been tested with Node v18 and Angular v16.2.0. This example should work with other compatible versions of Node and Angular. ## General Architecture While this sample application doesn't have login functionality without FusionAuth, a more typical integration will replace an existing login system with FusionAuth. In that case, the system might look like this before FusionAuth is introduced. ```mermaid sequenceDiagram participant User participant App as Application User ->> App : View Homepage User ->> App : Click Login Link App ->> User : Show Login Form User ->> App : Fill Out and Submit Login Form App ->> App : Authenticates User App ->> User : Display User's Account or Other Info ``` Request flow during login before FusionAuth And here's the same application login flow after introducing FusionAuth. ```mermaid sequenceDiagram participant User participant App as Application participant FusionAuth User ->> App : View Homepage User ->> App : Click Login Link (to FusionAuth) User ->> FusionAuth : View Login Form FusionAuth ->> User : Show Login Form User ->> FusionAuth : Fill Out and Submit Login Form FusionAuth ->> FusionAuth : Authenticates User FusionAuth ->> User: Go to Redirect URI User ->> App: Request the Redirect URI App ->> FusionAuth : Is User Authenticated? FusionAuth ->> App : User is Authenticated App ->> User : Display User's Account or Other Info ``` Request flow during login after FusionAuth In general, you are introducing FusionAuth in order to normalize and consolidate user data. This helps make sure it is consistent and up-to-date as well as offloading your login security and functionality to FusionAuth. ## Getting Started In this section, you'll get FusionAuth up and running and use Angular CLI to create a new application. ### Clone the Code First off, grab the code from the repository and change into that directory. ```shell-session $ git clone https://github.com/FusionAuth/fusionauth-quickstart-javascript-angular-web.git ``` ```shell-session $ cd fusionauth-quickstart-javascript-angular-web ``` ### Run FusionAuth via Docker You'll find a Docker Compose file (`docker-compose.yml`) and an environment variables configuration file (`.env`) in the root directory of the repo. Assuming you have Docker installed, you can stand up FusionAuth on your machine with the following. ```shell-session $ docker compose up -d ``` Here you are using a bootstrapping feature of FusionAuth called [Kickstart](https://4002.18-224-161-104.sslip.io/docs/get-started/download-and-install/development/kickstart.md). When FusionAuth comes up for the first time, it will look at the `kickstart/kickstart.json` file and configure FusionAuth to your specified state. Note If you ever want to reset the FusionAuth application, you need to delete the volumes created by Docker Compose by executing `docker compose down -v`, then re-run `docker compose up -d`. FusionAuth will be initially configured with these settings: * Your client Id is `e9fdb985-9173-4e01-9d73-ac2d60d1dc8e`. * Your client secret is `super-secret-secret-that-should-be-regenerated-for-production`. * Your example username is `richard@example.com` and the password is `password`. * Your admin username is `admin@example.com` and the password is `password`. * The base URL of FusionAuth is `http://localhost:9011/`. You can log in to the [FusionAuth admin UI](http://localhost:9011/admin) and look around if you want to, but with Docker and Kickstart, everything will already be configured correctly. Note If you want to see where the FusionAuth values came from, they can be found in the [FusionAuth app](http://localhost:9011/admin). The tenant Id is found on the Tenants page. To see the Client Id and Client Secret, go to the Applications page and click the `View` icon under the actions for the ChangeBank application. You'll find the Client Id and Client Secret values in the `OAuth configuration` section. Caution The `.env` file contains passwords. In a real application, always add this file to your `.gitignore` file and never commit secrets to version control. ### Create a basic Angular application Now you are going to create a basic Angular application using the Angular CLI. While this section builds a simple Angular application, you can use the same configuration to integrate your existing Angular application with FusionAuth. ```shell-session $ npx @angular/cli new changebank && cd changebank ``` You'll be prompted to answer a few questions about your application. You can choose the defaults for all of them. #### Create the Application We are going to use the [Hosted Backend](https://4002.18-224-161-104.sslip.io/docs/apis/hosted-backend.md) feature of FusionAuth, so you don't need to worry about setting up a backend server. Caution While this example uses localhost for your application and FusionAuth, there are complications if you plan to deploy using FusionAuth Cloud. When developing against a FusionAuth Cloud instance with a hostname ending in `fusionauth.io`, unless your application shares the same domain of `fusionauth.io` attempts to use these endpoints will fail with a `403` status code. These endpoints do not work correctly for cross origin requests. Cross origin requests occur when the application making the request to FusionAuth is using a separate domain. For example, if your application URL is `app.acme.com` and the FusionAuth URL is `acme.fusionauth.io` requests from your application to FusionAuth will be considered cross origin. If possible, have FusionAuth and your application served by the same domain, using a [proxy if needed](https://4002.18-224-161-104.sslip.io/docs/operate/deploy/proxy-setup.md). For example, serve your app from `app.acme.com` and FusionAuth from `auth.acme.com`. If this configuration is not possible, use one of these alternative methods: * Develop using a local FusionAuth instance, so both your webapp and FusionAuth are running on `localhost`. * Do not use the FusionAuth hosted backend, and instead write your own backend with a cross origin cookie policy: [here’s an example](https://github.com/FusionAuth/fusionauth-javascript-sdk-express/tree/main). * Configure a [custom domain name for the FusionAuth Cloud instance](https://4002.18-224-161-104.sslip.io/docs/cloud/operate/custom-domains.md). Modifying FusionAuth CORS configuration options does not fix this issue because the cookies that FusionAuth writes will not be accessible cross domain. First, install the FusionAuth Angular SDK: ```shell-session $ npm install @fusionauth/angular-sdk ``` Next, you'll need to configure the SDK with your FusionAuth URL and Client Id. You can do this by adding the following to your `src/app/app.module.ts` file inside the `imports: [ ]` section: ```typescript FusionAuthModule.forRoot({ clientId: 'e9fdb985-9173-4e01-9d73-ac2d60d1dc8e', serverUrl: 'http://localhost:9011', redirectUri: 'http://localhost:4200', postLogoutRedirectUri: 'http://localhost:4200/logged-out', scope: 'openid email profile offline_access', shouldAutoRefresh: true, }), ``` Don't forget to import the `FusionAuthModule` at the top of the file. ```typescript import { FusionAuthModule } from '@fusionauth/angular-sdk'; ``` Our example application is going to have a home page, an account page and a page where someone can make change. The account and make change page will be protected and only visible to logged in users. #### Create a Home Page The next step is to get a basic home page up and running. We'll take this opportunity to copy in all the images and CSS style files that you'll need for the application. Run the following copy commands to copy these files from the QuickStart repo into your project. This assumes that you checked the QuickStart repo out into the parent directory. If that's not the case, replace the `..` below with your actual repo location. ```shell-session $ cp -r ../complete-application/src/assets src && \ cp -r ../complete-application/src/styles.css src ``` The home page will be a simple page with a welcome message and a login link. You can create a new component for this page with the Angular CLI: ```shell-session $ npx ng generate component home-page --standalone ``` Then, add the welcome message and login link to the `src/app/home-page/home-page.component.html` template by replacing the contents of that file with the below contents: ```html

Welcome to Changebank

Login or create a new account to get started


Coins
``` And the login function to the component `src/app/home-page/home-page.component.ts`. Update that file to look like this: ```typescript import { Component, inject } from '@angular/core'; import { FusionAuthService } from '@fusionauth/angular-sdk'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-home-page', standalone: true, imports: [CommonModule], templateUrl: './home-page.component.html', styleUrls: ['./home-page.component.css'], }) export class HomePageComponent { private fusionAuthService = inject(FusionAuthService); login() { this.fusionAuthService.startLogin(); } register() { this.fusionAuthService.startRegistration(); } } ``` #### Create an Account Page The account page displays a random balance for the logged in user. You can create a new component for this page with the Angular CLI: ```shell-session $ npx ng generate component account-page --standalone ``` Then, display the balance in the `src/app/account-page/account-page.component.html` template by replacing the default content with the below: ```html

Your Balance

{{balance | currency}}
``` You'll need the balance property in the component `src/app/account-page/account-page.component.ts`. Update that file to look like this content: ```typescript import { Component } from '@angular/core'; import {CommonModule} from "@angular/common"; @Component({ selector: 'app-account-page', standalone: true, imports: [CommonModule], templateUrl: './account-page.component.html', styleUrls: ['./account-page.component.css'] }) export class AccountPageComponent { balance = Math.ceil(Math.random() * 100000) / 100; } ``` #### Create A Make Change Page Next, you'll create a page only visible to logged in users. This page displays an input field for the user to enter a dollar amount and a button to convert that amount into coins. You can create a new component for this page with the Angular CLI: ```shell-session $ npx ng generate component make-change-page --standalone ``` Then, add the input field and button to the `src/app/make-change-page/make-change-page.component.html` template, replacing the current contents: ```html

Make Change

Amount in USD
We can make change for {{change.total | currency}} with {{change.nickels}} nickels and {{change.pennies}} pennies!
``` You'll also need the make change function to the component `src/app/make-change-page/make-change-page.component.ts`. Here is the full contents of that file: ```typescript import { Component } from '@angular/core'; import {CommonModule} from "@angular/common"; import {FormsModule} from "@angular/forms"; @Component({ selector: 'app-make-change-page', standalone: true, imports: [CommonModule, FormsModule], templateUrl: './make-change-page.component.html', styleUrls: ['./make-change-page.component.css'] }) export class MakeChangePageComponent { amount = 0; change: { total: number; nickels: number; pennies: number } | null = null; makeChange() { // work in whole cents so floating-point rounding can't drop a penny const cents = Math.round(this.amount * 100); const nickels = Math.floor(cents / 5); const pennies = cents % 5; this.change = {nickels, pennies, total: cents / 100}; } } ``` ## Authentication You now have created a basic Angular application with a home page, account page and a page for making change. The next step is to add authentication to the application. ### Auth Guard The first step is to create an Auth Guard. This will be used to protect the account page and only allow logged in users to access it. Create a new file called `auth-guard.ts` in the `src/app` directory: ```typescript import {CanActivateFn, Router} from "@angular/router"; import {FusionAuthService} from "@fusionauth/angular-sdk"; import {inject} from "@angular/core"; export function authGuard(loggedIn: boolean, redirect: string): CanActivateFn { return () => { const fusionAuthService = inject(FusionAuthService); const router = inject(Router); return fusionAuthService.isLoggedIn() === loggedIn || router.createUrlTree([redirect]); } } ``` The Auth Guard is a functional router guard, which can be used to handle anonymous and logged in states. The first parameter defines if the guard should allow logged in users `true` or anonymous users `false`. The second parameter is the route to redirect to if the guard fails. ### Routing Next, you'll need to add the Auth Guard to the routing configuration. Open the `src/app/app.module.ts` file and add the RouterModule with the following routes inside the `imports: [ ]` part: ```typescript RouterModule.forRoot([ { path: '', loadComponent: () => import('./home-page/home-page.component').then( (m) => m.HomePageComponent ), canActivate: [authGuard(false, '/account')], }, { path: 'logged-out', loadComponent: () => import('./home-page/home-page.component').then( (m) => m.HomePageComponent ), canActivate: [authGuard(false, '/account')], }, { path: 'account', loadComponent: () => import('./account-page/account-page.component').then( (m) => m.AccountPageComponent ), canActivate: [authGuard(true, '/')], }, { path: 'make-change', loadComponent: () => import('./make-change-page/make-change-page.component').then( (m) => m.MakeChangePageComponent ), canActivate: [authGuard(true, '/')], }, ]), ``` Don't forget to import the `RouterModule` and `authGuard` at the top of the file. ```typescript import { RouterModule } from '@angular/router'; import { authGuard } from './auth-guard'; ``` ### Tie it all together Now that you have the Auth Guard and the routing configured, you can tie it all together. Open the `src/app/app.component.html` file and replace its content with the following: ```html
``` Finally, open the `src/app/app.component.ts` file and replace it with the following: ```typescript import { Component, OnDestroy, OnInit, inject } from '@angular/core'; import { FusionAuthService, UserInfo } from '@fusionauth/angular-sdk'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit, OnDestroy { private fusionAuthService: FusionAuthService = inject(FusionAuthService); isLoggedIn: boolean = this.fusionAuthService.isLoggedIn(); userInfo: UserInfo | null = null; isGettingUserInfo: boolean = false; subscription?: Subscription; ngOnInit(): void { if (this.isLoggedIn) { this.subscription = this.fusionAuthService .getUserInfoObservable({ onBegin: () => (this.isGettingUserInfo = true), onDone: () => (this.isGettingUserInfo = false), }) .subscribe({ next: (userInfo) => (this.userInfo = userInfo), error: (error) => console.error(error), }); } } ngOnDestroy(): void { this.subscription?.unsubscribe(); } logout() { this.fusionAuthService.logout(); } login() { this.fusionAuthService.startLogin(); } } ``` ## Running the Application You can now run the application with the following command: ```shell-session $ npm start ``` You can now open up an incognito window and navigate to [http://localhost:4200](http://localhost:4200). You will be greeted with the home page. Log in with the user account you created when setting up FusionAuth, and you'll be redirected to the account page. Note The username and password of the `Example user` can be found in the [FusionAuth via Docker](#run-fusionauth-via-docker) section at the top of this article. ## Made it this far? Want a free t-shirt? We got ya. Thank you for spending some time getting familiar with FusionAuth. \*Offer only valid in the United States and Canada, while supplies last. [fusionauth tshirt](https://go.fusionauth.io/tshirt) ## Next Steps This QuickStart is a great way to get a proof of concept up and running quickly, but to run your application in production, there are some things you're going to want to do. ### FusionAuth Customization FusionAuth gives you the ability to customize just about everything to do with the user's experience and the integration of your application. This includes: * [Hosted pages](https://4002.18-224-161-104.sslip.io/docs/theme.md) such as login, registration, email verification, and many more. * [Email templates](https://4002.18-224-161-104.sslip.io/docs/email/email-templates.md). * [User data and custom claims in access token JWTs](https://4002.18-224-161-104.sslip.io/articles/tokens/jwt-components-explained.md). ### Security * You may want to customize the [token expiration times and policies](https://4002.18-224-161-104.sslip.io/docs/lifecycle/authenticate-users/oauth.md) in FusionAuth. * Choose [password rules](https://4002.18-224-161-104.sslip.io/docs/get-started/core-concepts/types/tenants.md#password) and a [hashing algorithm](https://4002.18-224-161-104.sslip.io/docs/reference/password-hashes.md) that meet your security needs. ### Tenant and Application Management * Model your application topology using [Applications](https://4002.18-224-161-104.sslip.io/docs/get-started/core-concepts/types/applications.md), [Roles](https://4002.18-224-161-104.sslip.io/docs/get-started/core-concepts/types/roles.md), [Groups](https://4002.18-224-161-104.sslip.io/docs/get-started/core-concepts/types/groups.md), [Entities](https://4002.18-224-161-104.sslip.io/docs/get-started/core-concepts/types/groups.md), and more. * Set up [MFA](https://4002.18-224-161-104.sslip.io/docs/lifecycle/authenticate-users/multi-factor-authentication.md), [Social login](https://4002.18-224-161-104.sslip.io/docs/lifecycle/authenticate-users/identity-providers.md), or [SAML](https://4002.18-224-161-104.sslip.io/docs/lifecycle/authenticate-users/identity-providers/overview-samlv2.md) integrations. * Integrate with external systems using [Webhooks](https://4002.18-224-161-104.sslip.io/docs/extend/events-and-webhooks.md), [SCIM](https://4002.18-224-161-104.sslip.io/docs/lifecycle/migrate-users/scim.md), and [Lambdas](https://4002.18-224-161-104.sslip.io/docs/extend/code/lambdas.md). Related [Get Started FusionAuth QuickStart for Vue.js QuickStart integration of a Vue.js web application with FusionAuth. spa authentication](https://4002.18-224-161-104.sslip.io/docs/get-started/quickstarts/spa/quickstart-javascript-vue-web.md) [Get Started FusionAuth QuickStart for React QuickStart a React Web App with FusionAuth. spa authentication](https://4002.18-224-161-104.sslip.io/docs/get-started/quickstarts/spa/react.md) [SDKs Angular SDK The FusionAuth Angular SDK allows you to add login, logout and registration functionality to your Angular application. spa authentication](https://4002.18-224-161-104.sslip.io/docs/sdks/angular-sdk.md) [SDKs React SDK The FusionAuth React SDK allows you to add login, logout and registration functionality to your React application. spa authentication](https://4002.18-224-161-104.sslip.io/docs/sdks/react-sdk.md) --- ## Other pages in Spa > For the full index of this section, see [Get Started](https://4002.18-224-161-104.sslip.io/docs/llms-get-started.txt). - [Single-page App](https://4002.18-224-161-104.sslip.io/docs/get-started/quickstarts/spa.md): Explore step-by-step single-page application QuickStart guides from FusionAuth to seamlessly integrate authentication into your application. - [FusionAuth QuickStart for Vue.js](https://4002.18-224-161-104.sslip.io/docs/get-started/quickstarts/spa/quickstart-javascript-vue-web.md): QuickStart integration of a Vue.js web application with FusionAuth. - [FusionAuth QuickStart for React](https://4002.18-224-161-104.sslip.io/docs/get-started/quickstarts/spa/react.md): QuickStart a React Web App with FusionAuth.