Angular SDK

On this page

The Angular SDK manages authentication state for your Angular application. The SDK provides functions to log in, register, and log out users, and you can configure the SDK to refresh tokens automatically.

FusionAuth sends your users to the themeable hosted login pages. After login, FusionAuth sends your users back to your Angular application.

When authentication succeeds, the server sets these secure, HTTP-only cookies:

  • app.at: an OAuth access token.
  • app.rt: a refresh token that the SDK uses to get a new app.at. The server sets this cookie only when you enable refresh tokens on your FusionAuth instance.

Present the access token to your APIs to authorize requests. Use the refresh token to get a new access token.

The SDK works with either of these servers:

The SDK works with any version of FusionAuth and any OIDC-compliant identity server.

Install#

For a full tutorial on FusionAuth and Angular, see the FusionAuth Angular Quickstart.

To install the SDK with npm, run:

npm install @fusionauth/angular-sdk

To install the SDK with Yarn, run:

yarn add @fusionauth/angular-sdk

Configure the SDK#

Add FusionAuthModule.forRoot() to the imports of your application module:

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

import { AppRoutingModule } from './app-routing.module';
import { FusionAuthModule } from '@fusionauth/angular-sdk';

@NgModule({
  declarations: [],
  imports: [
    FusionAuthModule.forRoot({
      clientId: '', // Your FusionAuth client Id
      serverUrl: '', // The base URL of the server that performs the token exchange
      redirectUri: '', // The URI that the user is directed to after the login/register/logout action
      shouldAutoRefresh: true // option to configure the SDK to automatically handle token refresh. Defaults to false if not specified here.
      // useDpop: true, // Opt-in to DPoP mode. See "Use DPoP Mode" below. Defaults to false.
    }),
  ],
  providers: [],
  bootstrap: []
})
export class AppModule { }

For a full list of configuration options, see Web SDK Configuration.

Usage#

Use FusionAuthService#

The injectable FusionAuthService class provides observable properties that components can subscribe to. To build your own observables, use the non-observable getUserInfo method instead.

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();
  }
}

Use the Pre-Built Buttons#

The SDK includes pre-styled login, logout, and registration buttons. Place the buttons anywhere in your application without further configuration:

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

@Component({
  selector: 'app-login',
  template: `<fa-login></fa-login>`,
  styleUrls: []
})
export class LoginComponent {}

@Component({
  selector: 'app-logout',
  template: `<fa-logout></fa-logout>`,
  styleUrls: []
})
export class LogoutComponent {}

@Component({
  selector: 'app-register',
  template: `<fa-register></fa-register>`,
  styleUrls: []
})
export class RegisterComponent {}

Pass State Through Login#

The startLogin and startRegistration functions accept an optional string parameter named state. The login and register components accept state as an input. FusionAuth returns the value in the state query parameter of the callback URI that you set in redirectUri on the FusionAuthConfig. You can pass any value. A common choice is the page the user was on before login, so your application can return the user to that page after authentication.

Use Server-Side Rendering#

The SDK supports Angular applications that use server-side rendering. The SDK needs no additional configuration.

Use DPoP Mode#

By default, the SDK calls a hosted backend that stores tokens in HttpOnly cookiesA cookie that the browser sends with requests but hides from JavaScript, so a cross-site scripting attack can't read the cookie.. In DPoP mode, the SDK calls FusionAuth endpoints directly and binds tokens to a private key that the browser generates. To enable DPoP mode, set useDpop to true on FusionAuthConfig. The default is false.

The following configuration enables DPoP mode:

FusionAuthModule.forRoot({
  clientId: '',
  serverUrl: '',
  redirectUri: '',
  useDpop: true, // Opt-in to DPoP mode.
  dpopTokenStorage: 'localStorage', // 'localStorage' (default, persists across reloads) or 'memory'.
}),

When useDpop is true, FusionAuthService also exposes dpopFetch(), generateProof(), and getAccessToken(). These methods throw a descriptive error when useDpop is not enabled.

The following code calls an API with each method:

class AppComponent {
  private fusionAuthService: FusionAuthService = inject(FusionAuthService);

  async callApi() {
    // Recommended: attaches DPoP headers and retries nonce errors automatically.
    const response = await this.fusionAuthService.dpopFetch('https://api.example.com/data', { method: 'GET' });

    // For axios or other HTTP libraries that can't use dpopFetch.
    const accessToken = this.fusionAuthService.getAccessToken();
    const proof = await this.fusionAuthService.generateProof('https://api.example.com/data', 'GET', accessToken ?? undefined);
    // axios.get('https://api.example.com/data', {
    //   headers: { Authorization: `DPoP ${accessToken}`, DPoP: proof }
    // });
  }
}

Library Documentation#

For more information, see the full library documentation.

Use the SDK with 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. 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:

Modifying FusionAuth CORS configuration options does not fix this issue because the cookies that FusionAuth writes will not be accessible cross domain.

Source Code#

The SDK source code is on GitHub.

Update Policy#

FusionAuth releases new versions of the SDKs and client libraries to track the FusionAuth API. SDKs and client libraries may also receive bug fixes, security patches, tests, code samples, and documentation changes.

These releases may update dependencies, language engines, and operating systems, because FusionAuth follows the deprecation and sunsetting policies of the underlying technologies. When the maintainer deprecates a language, framework, or operating system, FusionAuth deprecates the SDKs and client libraries that depend on the technology. FusionAuth then updates the SDKs and client libraries to use a newer version.

For more information, see Update a Client Library.