> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Angularアプリケーションにログインを追加する

> このガイドでは、Auth0 Angular SDK を使用して、任意の Angular アプリケーションに Auth0 を統合し、認証を追加して、ユーザープロファイル情報を表示する方法を説明します。

> [accordion] AI を使って Auth0 を統合する
>
> Claude Code、Cursor、GitHub Copilot のような AI コーディングアシスタントを使えば、[agent skills](https://agentskills.io/home) を利用して、数分で Auth0 の認証を自動的に追加できます。
>
> **インストール:**
>
> ```bash theme={null}
> npx skills add auth0/agent-skills --skill auth0
> ```
>
> **次に、AI アシスタントにこう依頼します。**
>
> ```text theme={null}
> Add Auth0 authentication to my Angular app
> ```
>
> AI アシスタントが、Auth0 アプリケーションの作成、資格情報の取得、`@auth0/auth0-angular` のインストール、ルートガードや HTTP インターセプターの作成、環境設定まで自動的に行います。[agent skills の完全なドキュメント →](/docs/docs/ja-jp/quickstart/agent-skills)

> [!NOTE]
>
> **前提条件:** 始める前に、次のものがインストールされていることを確認してください。
>
> * **[Node.js](https://nodejs.org/en/download)** 20 LTS 以降
> * **[npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)** 10 以降、または **[yarn](https://classic.yarnpkg.com/lang/en/docs/install/)** 1.22 以降、または **[pnpm](https://pnpm.io/installation)** 8 以降
> * **[jq](https://jqlang.org/)** - Auth0 CLI のセットアップに必要です
>
> インストール確認: `node --version && npm --version`
>
> **Angular のバージョン互換性:** このクイックスタートは、Angular CLI を使用する **Angular 19〜21** で動作します。`@auth0/auth0-angular` SDK は Angular 13 以降をサポートしています。

## はじめに

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

**1. 新しいプロジェクトを作成**

このQuickstart用に、新しいAngularプロジェクトを作成します

```shellscript theme={null}
npx @angular/cli@latest new auth0-angular --routing=true --style=css
```

プロジェクトを開く

```shellscript theme={null}
cd auth0-angular
```

**2. Auth0 Angular SDK をインストール**

```shellscript theme={null}
npm install @auth0/auth0-angular && npm install
```

**3. Auth0 Appをセットアップする**

次に、Auth0 テナントで新しいアプリを作成し、プロジェクトに環境変数を追加します。

Auth0アプリのセットアップ方法は3つあります。Quick Setupツールを使用する (推奨) 、CLIコマンドを実行する、またはAuth0 Dashboardから手動で設定するかのいずれかを選択できます。

> [tab] クイック設定（推奨）
>
> Auth0 App を作成し、適切な設定値があらかじめ設定された `.env` ファイルをコピーします。

> [tab] CLI
>
> Auth0 アプリを作成して環境ファイルを生成するには、プロジェクトのルートディレクトリで次のシェルコマンドを実行します。
>
> ```shellscript Mac theme={null}
> # Auth0 CLIをインストール（まだインストールしていない場合）
> brew tap auth0/auth0-cli && brew install auth0
>
> # Auth0アプリをセットアップし、環境ファイルを生成
> auth0 qs setup --app --type spa --framework angular --name "My Angular App" --port 4200
> ```
>
> ```powershell Windows theme={null}
> # Auth0 CLIをインストール（まだインストールしていない場合）
> scoop bucket add auth0 https://github.com/auth0/scoop-auth0-cli.git
> scoop install auth0
>
> # Auth0アプリをセットアップし、環境ファイルを生成
> auth0 qs setup --app --type spa --framework angular --name "My Angular App" --port 4200
> ```
>
> > [!NOTE]
> >
> > このコマンドは次の処理を行います：
> >
> > 1. 認証済みかどうかを確認します (必要に応じてログインを求められます)
> > 2. `http://localhost:4200` 用に設定されたAuth0 Single Page Applicationを作成します
> > 3. Auth0のドメインとクライアントIDを含む `src/environments/environment.ts` を生成します

> [tab] Auth0 Dashboard
>
> 始める前に、プロジェクト内に環境ファイルを作成してください
>
> ```typescript src/environments/environment.ts theme={null}
> export const environment = {
>   production: false,
>   auth0: {
>     domain: 'YOUR_AUTH0_APP_DOMAIN',
>     clientId: 'YOUR_AUTH0_APP_CLIENT_ID'
>   }
> };
> ```
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/dashboard/)を開きます
> 2. **アプリケーション** > **アプリケーション** > **アプリケーションを作成** をクリックします
> 3. ポップアップでアプリ名を入力し、アプリの種類として `Single Page Web Application` を選択して、**作成** をクリックします
> 4. アプリケーションの詳細ページで **設定** タブに切り替えます
> 5. `src/environments/environment.ts` ファイル内の `YOUR_AUTH0_APP_DOMAIN` と `YOUR_AUTH0_APP_CLIENT_ID` を、Auth0 Dashboard の **Domain** と **Client ID** の値に置き換えます
>
> 最後に、アプリケーションの詳細ページの **設定** タブで、次の URL を設定します。
>
> **Allowed Callback URLs:**
>
> ```
> http://localhost:4200
> ```
>
> **許可されたログアウトURL:**
>
> ```
> http://localhost:4200
> ```
>
> **許可済みのWebオリジン:**
>
> ```
> http://localhost:4200
> ```
>
> > [!NOTE]
> >
> > **Allowed Callback URLs** は、認証後にユーザーを安全にアプリケーションへ戻すための重要なセキュリティ対策です。一致するURLがない場合、ログインプロセスは失敗し、ユーザーにはAuth0のエラーページが表示されて、アプリにアクセスできなくなります。
> >
> > **Allowed Logout URLs** は、サインアウト時にスムーズなユーザー体験を提供するうえで不可欠です。一致するURLがない場合、ユーザーはログアウト後にアプリケーションへリダイレクトされず、代わりにAuth0の汎用ページに留まることになります。
> >
> > **Allowed Web Origins** は、サイレント認証において重要です。これがないと、ユーザーはページを更新したときや、後でアプリに戻ったときにログアウトされます。

**4. Auth0 モジュールを設定する**

前の手順で環境ファイルを用意したら、`app.config.ts` の providers 配列に `provideAuth0` を追加します。

```typescript src/app/app.config.ts {3,4,5,11-17} lines theme={null}
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
      }
    })
  ]
};
```

> [!NOTE]
>
> Auth0 アプリをダッシュボードから手動で設定する場合は、ダッシュボードに表示されるドメインと client ID を使って `src/environments/environment.ts` を作成してください。
>
> Angular 20 以降のプロジェクトでは、このファイルに `provideBrowserGlobalErrorListeners()` も含まれています。`provideAuth0` と一緒に配列内にそのまま残してください。`main.ts` を変更する必要はありません。

**5. ログイン、ログアウト、プロファイルの各コンポーネントを作成**

Angular CLI を使用してコンポーネントファイルを生成します：

```shellscript theme={null}
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コンポーネントを更新し、スタイルを追加します：

> [tab] App コンポーネント
>
> アプリのコンポーネントファイル (Angular 20以降では `src/app/app.ts`、Angular 19では `src/app/app.component.ts`) の内容を置き換えます:
>
> ```typescript src/app/app.ts expandable lines theme={null}
> 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);
> }
> ```

> [tab] グローバルスタイル
>
> `src/styles.css` にスタイルを追加します：
>
> ```css src/styles.css expandable lines theme={null}
> @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
>
> body {
>   margin: 0;
>   font-family: 'Inter', sans-serif;
>   background-color: #1a1e27;
>   min-height: 100vh;
>   display: flex;
>   justify-content: center;
>   align-items: center;
>   color: #e2e8f0;
>   overflow: hidden;
> }
>
> #root {
>   width: 100%;
>   height: 100%;
>   display: flex;
>   justify-content: center;
>   align-items: center;
> }
>
> .app-container {
>   display: flex;
>   flex-direction: column;
>   justify-content: center;
>   align-items: center;
>   min-height: 100vh;
>   width: 100%;
>   padding: 1rem;
>   box-sizing: border-box;
> }
>
> .loading-state, .error-state {
>   background-color: #2d313c;
>   border-radius: 15px;
>   box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
>   padding: 3rem;
>   text-align: center;
> }
>
> .loading-text {
>   font-size: 1.8rem;
>   font-weight: 500;
>   color: #a0aec0;
>   animation: pulse 1.5s infinite ease-in-out;
> }
>
> .error-state {
>   background-color: #c53030;
>   color: #fff;
> }
>
> .error-title {
>   font-size: 2.8rem;
>   font-weight: 700;
>   margin-bottom: 0.5rem;
> }
>
> .error-message {
>   font-size: 1.3rem;
>   margin-bottom: 0.5rem;
> }
>
> .error-sub-message {
>   font-size: 1rem;
>   opacity: 0.8;
> }
>
> .main-card-wrapper {
>   background-color: #262a33;
>   border-radius: 20px;
>   box-shadow: 0 20px 60px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05);
>   display: flex;
>   flex-direction: column;
>   align-items: center;
>   gap: 2rem;
>   padding: 3rem;
>   max-width: 500px;
>   width: 90%;
>   animation: fadeInScale 0.8s ease-out forwards;
> }
>
> .auth0-logo {
>   width: 160px;
>   margin-bottom: 1.5rem;
>   opacity: 0;
>   animation: slideInDown 1s ease-out forwards 0.2s;
> }
>
> .main-title {
>   font-size: 2.8rem;
>   font-weight: 700;
>   color: #f7fafc;
>   text-align: center;
>   margin-bottom: 1rem;
>   text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
>   opacity: 0;
>   animation: fadeIn 1s ease-out forwards 0.4s;
> }
>
> .action-card {
>   background-color: #2d313c;
>   border-radius: 15px;
>   box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3), 0 5px 15px rgba(0, 0, 0, 0.3);
>   padding: 2.5rem;
>   display: flex;
>   flex-direction: column;
>   align-items: center;
>   gap: 1.8rem;
>   width: calc(100% - 2rem);
>   opacity: 0;
>   animation: fadeIn 1s ease-out forwards 0.6s;
> }
>
> .action-text {
>   font-size: 1.25rem;
>   color: #cbd5e0;
>   text-align: center;
>   line-height: 1.6;
>   font-weight: 400;
> }
>
> .button {
>   padding: 1.1rem 2.8rem;
>   font-size: 1.2rem;
>   font-weight: 600;
>   border-radius: 10px;
>   border: none;
>   cursor: pointer;
>   transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
>   box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
>   text-transform: uppercase;
>   letter-spacing: 0.08em;
>   outline: none;
> }
>
> .button:focus {
>   box-shadow: 0 0 0 4px rgba(99, 179, 237, 0.5);
> }
>
> .button.login {
>   background-color: #63b3ed;
>   color: #1a1e27;
> }
>
> .button.login:hover {
>   background-color: #4299e1;
>   transform: translateY(-5px) scale(1.03);
>   box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5);
> }
>
> .button.logout {
>   background-color: #fc8181;
>   color: #1a1e27;
> }
>
> .button.logout:hover {
>   background-color: #e53e3e;
>   transform: translateY(-5px) scale(1.03);
>   box-shadow: 0 12px 25px rgba(0, 0, 0, 0.5);
> }
>
> .logged-in-section {
>   display: flex;
>   flex-direction: column;
>   align-items: center;
>   gap: 1.5rem;
>   width: 100%;
> }
>
> .logged-in-message {
>   font-size: 1.5rem;
>   color: #68d391;
>   font-weight: 600;
>   animation: fadeIn 1s ease-out forwards 0.8s;
> }
>
> .profile-section-title {
>   font-size: 2.2rem;
>   animation: slideInUp 1s ease-out forwards 1s;
> }
>
> .profile-card {
>   padding: 2.2rem;
>   animation: scaleIn 0.8s ease-out forwards 1.2s;
> }
>
> .profile-picture {
>   width: 110px;
>   transition: transform 0.3s ease-in-out;
> }
>
> .profile-picture:hover {
>   transform: scale(1.05);
> }
>
> .profile-name {
>   font-size: 2rem;
>   margin-top: 0.5rem;
> }
>
> .profile-email {
>   font-size: 1.15rem;
>   text-align: center;
> }
>
> @keyframes fadeIn {
>   from { opacity: 0; }
>   to { opacity: 1; }
> }
>
> @keyframes fadeInScale {
>   from { opacity: 0; transform: scale(0.95); }
>   to { opacity: 1; transform: scale(1); }
> }
>
> @keyframes slideInDown {
>   from { opacity: 0; transform: translateY(-70px); }
>   to { opacity: 1; transform: translateY(0); }
> }
>
> @keyframes slideInUp {
>   from { opacity: 0; transform: translateY(50px); }
>   to { opacity: 1; transform: translateY(0); }
> }
>
> @keyframes pulse {
>   0%, 100% { opacity: 1; }
>   50% { opacity: 0.6; }
> }
>
> @keyframes scaleIn {
>   from { opacity: 0; transform: scale(0.8); }
>   to { opacity: 1; transform: scale(1); }
> }
>
> @media (max-width: 600px) {
>   .main-card-wrapper {
>     padding: 2rem;
>     margin: 1rem;
>   }
>
>   .main-title {
>     font-size: 2.2rem;
>   }
>
>   .button {
>     padding: 1rem 2rem;
>     font-size: 1.1rem;
>   }
>
>   .auth0-logo {
>     width: 120px;
>   }
> }
> ```

**6. アプリを起動する**

```shellscript theme={null}
ng serve
```

> [!NOTE]
>
> ポート4200が使用中の場合は、`ng serve --port 4201` を実行し、Auth0アプリのコールバックURLを `http://localhost:4201` に変更してください

> [!TIP]
>
> **チェックポイント**
>
> これで、[localhost](http://localhost:4200/) 上で完全に機能する Auth0 のログインページが動作しているはずです

***

## 高度な使い方

> [accordion] 従来の NgModule アプローチを使う
>
> `--standalone=false` でプロジェクトを作成した場合や、standalone コンポーネントではなく NgModule を使いたい場合は、Angular 20+ の CLI 生成プロジェクトで SDK を次のように設定します。
>
> ```typescript src/main.ts theme={null}
> import { platformBrowser } from '@angular/platform-browser';
> import { AppModule } from './app/app-module';
>
> platformBrowser().bootstrapModule(AppModule)
>   .catch((err) => console.error(err));
> ```
>
> ```typescript src/app/app-module.ts theme={null}
> 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 { }
> ```
>
> > [!NOTE]
> >
> > **Angular 19** を使用している場合、生成されるファイルは通常 `app.component.ts`、`app.module.ts`、`app-routing.module.ts` で、`main.ts` では `platformBrowser` ではなく `platformBrowserDynamic` を使用します。
> >
> > **Angular 20+** では、`app.ts`、`app-module.ts`、`app-routing-module.ts` が生成され (ファイル名にドットはありません) 、`main.ts` は上記のように `platformBrowser` を使用します。
> >
> > いずれの場合も、NgModule プロジェクトは、メインのクイックスタートで示した `bootstrapApplication()` アプローチではなく、`bootstrapModule()` でブートストラップします。

> [accordion] AuthGuard でルートを保護する
>
> 認証が必要なルートを保護するには、モダンな関数ベースのガードを使用します。
>
> ```typescript src/app/app.routes.ts theme={null}
> 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.ts` に `provideAuth0` とルーターを追加します (Step 4 でまだ追加していない場合) 。
>
> ```typescript src/app/app.config.ts theme={null}
> 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
>       }
>     })
>   ]
> };
> ```

> [accordion] 保護された API を呼び出す
>
> HTTP インターセプターを設定して、API 呼び出しに token を自動的に付与します。Auth0 インターセプターと `audience` を含む `provideHttpClient` を `app.config.ts` に追加します。
>
> ```typescript src/app/app.config.ts theme={null}
> 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])
>     )
>   ]
> };
> ```
