メインコンテンツへスキップ

AI で Auth0 を統合する

Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使用している場合は、agent skills を使って数分で Auth0 認証を自動的に追加できます。インストール:
npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-angular
次に、AI アシスタントに次のように依頼します。
Add Auth0 authentication to my Angular app
AI アシスタントは、Auth0 アプリケーションを自動的に作成し、認証情報を取得して、@auth0/auth0-angular をインストールし、ルートガードと HTTP インターセプターを作成し、環境を設定します。agent skills の完全なドキュメント →
前提条件: 始める前に、次のものがインストールされていることを確認してください。
  • Node.js 20 LTS 以降
  • npm 10 以上、または yarn 1.22 以上、または pnpm 8 以上
  • jq - Auth0 CLI のセットアップに必要
インストールを確認します: node --version && npm --versionAngular のバージョン互換性: このクイックスタートは、Angular CLI を使用する Angular 19〜21 で動作します。@auth0/auth0-angular SDK は Angular 13 以降をサポートしています。

はじめに

このクイックスタートでは、Angular アプリケーションに Auth0 認証を追加する方法を説明します。Angular の依存性注入システムと Auth0 Angular SDK を使用して、ログイン機能とログアウト機能を備えた安全なシングルページアプリケーションを構築します。
1

新規プロジェクトを作成する

このクイックスタート用に新しい Angular プロジェクトを作成します
npx @angular/cli@latest new auth0-angular --routing=true --style=css
プロジェクトを開く
cd auth0-angular
2

Auth0 Angular SDKをインストールする

npm install @auth0/auth0-angular && npm install
3

Auth0アプリの設定

次に、Auth0テナントで新しいアプリを作成し、プロジェクトに環境変数を追加します。Auth0アプリをセットアップするには、次の3つの方法があります。クイックセットアップツールを使用する (推奨) 、CLIコマンドを実行する、またはDashboardから手動で設定する方法です。
Auth0 アプリを作成し、適切な設定値があらかじめ入力された .env ファイルをコピーします。
4

Auth0 モジュールを設定する

前の手順で環境ファイルを用意したら、app.config.ts の providers 配列に provideAuth0 を追加します。
src/app/app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAuth0 } from '@auth0/auth0-angular';
import { environment } from '../environments/environment';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAuth0({
      domain: environment.auth0.domain,
      clientId: environment.auth0.clientId,
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    })
  ]
};
Auth0 アプリを Dashboard から手動で設定する場合は、Dashboard のドメインとクライアントIDを使用して src/environments/environment.ts を作成します。Angular 20+ のプロジェクトでは、このファイルに provideBrowserGlobalErrorListeners() も含まれます。provideAuth0 と並べて配列内に残しておいてください。main.ts を変更する必要はありません。
5

Login、ログアウト、ユーザープロファイルの各コンポーネントを作成

Angular CLIを使用してコンポーネントファイルを生成します:
ng generate component components/login-button --inline-template --inline-style --skip-tests && \
ng generate component components/logout-button --inline-template --inline-style --skip-tests && \
ng generate component components/profile --inline-template --inline-style --skip-tests
各コンポーネントに以下のコードを追加します。次に、メインのAppコンポーネントを更新し、スタイルを追加します。
アプリコンポーネントファイルの内容を置き換えます (Angular 20 以降では src/app/app.ts、Angular 19 では src/app/app.component.ts) :
src/app/app.ts
import { Component, inject } from '@angular/core';
import { AuthService } from '@auth0/auth0-angular';
import { CommonModule } from '@angular/common';
import { LoginButtonComponent } from './components/login-button.component';
import { LogoutButtonComponent } from './components/logout-button.component';
import { ProfileComponent } from './components/profile.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, LoginButtonComponent, LogoutButtonComponent, ProfileComponent],
  template: `
    <div class="app-container">
      <!-- 読み込み中の状態 -->
      @if (auth.isLoading$ | async) {
        <div class="loading-state">
          <div class="loading-text">Loading...</div>
        </div>
      }

      <!-- エラー状態 -->
      @if (auth.error$ | async; as error) {
        <div class="error-state">
          <div class="error-title">Oops!</div>
          <div class="error-message">Something went wrong</div>
          <div class="error-sub-message">{{ error.message }}</div>
        </div>
      }

      <!-- メインコンテンツ -->
      @if (!(auth.isLoading$ | async) && !(auth.error$ | async)) {
        <div class="main-card-wrapper">
          <img 
            src="https://cdn.auth0.com/quantum-assets/dist/latest/logos/auth0/auth0-lockup-en-ondark.png" 
            alt="Auth0 Logo" 
            class="auth0-logo"
          />
          <h1 class="main-title">Welcome to Sample0</h1>
          
          <!-- 認証済み状態 -->
          @if (auth.isAuthenticated$ | async) {
            <div class="logged-in-section">
              <div class="logged-in-message">✅ Successfully authenticated!</div>
              <h2 class="profile-section-title">Your Profile</h2>
              <div class="profile-card">
                <app-profile />
              </div>
              <app-logout-button />
            </div>
          } @else {
            <!-- 未認証状態 -->
            <div class="action-card">
              <p class="action-text">Get started by signing in to your account</p>
              <app-login-button />
            </div>
          }
        </div>
      }
    </div>
  `,
  styles: []
})
export class App {
  protected auth = inject(AuthService);
}
6

アプリを実行する

ng serve
ポート4200がすでに使用されている場合は、ng serve --port 4201 を実行し、Auth0 アプリのコールバックURLを http://localhost:4201 に更新してください
チェックポイントlocalhost 上で Auth0 のログインページが問題なく動作しているはずです

高度な使用方法

--standalone=false でプロジェクトを作成した場合や、スタンドアロンコンポーネントではなく NgModule を使用したい場合は、Angular 20+ の CLI 生成プロジェクトで SDK を次のように設定します。
src/main.ts
import { platformBrowser } from '@angular/platform-browser';
import { AppModule } from './app/app-module';

platformBrowser().bootstrapModule(AppModule)
  .catch((err) => console.error(err));
src/app/app-module.ts
import { NgModule, provideBrowserGlobalErrorListeners } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AuthModule } from '@auth0/auth0-angular';
import { environment } from '../environments/environment';

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

@NgModule({
  declarations: [App],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AuthModule.forRoot({
      domain: environment.auth0.domain,
      clientId: environment.auth0.clientId,
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    })
  ],
  providers: [provideBrowserGlobalErrorListeners()],
  bootstrap: [App]
})
export class AppModule { }
Angular 19 を使用している場合、生成されるファイルは通常 app.component.tsapp.module.tsapp-routing.module.ts で、main.ts では platformBrowser ではなく platformBrowserDynamic を使用します。Angular 20+ では app.tsapp-module.tsapp-routing-module.ts が生成されます (ファイル名にドットは含まれません) 。また、main.ts では上記のように platformBrowser を使用します。いずれの場合も、NgModule プロジェクトではメインのクイックスタートで示した bootstrapApplication() アプローチではなく、bootstrapModule() でブートストラップします。
認証が必要なルートを保護するには、最新の関数ベースのガードを使用します。
src/app/app.routes.ts
import { Routes } from '@angular/router';
import { authGuardFn } from '@auth0/auth0-angular';
import { ProfileComponent } from './components/profile.component';

export const routes: Routes = [
  {
    path: 'profile',
    component: ProfileComponent,
    canActivate: [authGuardFn]
  },
  {
    path: '',
    redirectTo: '/profile',
    pathMatch: 'full'
  }
];
次に、app.config.tsprovideAuth0 とルーターを追加します (手順 4 でまだ追加していない場合) 。
src/app/app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideAuth0 } from '@auth0/auth0-angular';
import { environment } from '../environments/environment';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAuth0({
      domain: environment.auth0.domain,
      clientId: environment.auth0.clientId,
      authorizationParams: {
        redirect_uri: window.location.origin
      }
    })
  ]
};
HTTP インターセプターを設定すると、API 呼び出しにトークンを自動的に付与できます。Auth0 インターセプターを含む provideHttpClientaudienceapp.config.ts に追加します。
src/app/app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideAuth0, authHttpInterceptorFn } from '@auth0/auth0-angular';
import { environment } from '../environments/environment';
import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [
    provideZoneChangeDetection({ eventCoalescing: true }),
    provideRouter(routes),
    provideAuth0({
      domain: environment.auth0.domain,
      clientId: environment.auth0.clientId,
      authorizationParams: {
        redirect_uri: window.location.origin,
        audience: 'YOUR_API_IDENTIFIER'
      },
      httpInterceptor: {
        allowedList: [
          'http://localhost:3001/api/*'
        ]
      }
    }),
    provideHttpClient(
      withInterceptors([authHttpInterceptorFn])
    )
  ]
};