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

# Flutter Windows アプリケーションにログイン機能を追加する

> このガイドでは、Auth0 Flutter SDK（Beta版）を使用して、Flutter Windows デスクトップアプリケーションに Auth0 を統合する方法を説明します。

> [!NOTE]
>
> **前提条件:**
>
> * Flutter SDK 3.24.0+ と Dart 3.5.0+。
> * Windows 10 以降。
> * **Desktop development with C++** ワークロードを含む Visual Studio 2022。
> * Auth0 アカウント — [無料でサインアップ](https://auth0.com/signup)。
>
> この機能は**Beta**版です (`auth0_flutter` 2.1.0-beta.1) 。API は一般提供前に変更される可能性があります。

このガイドでは、OAuth 2.0 の[認可コードフロー + PKCE](/docs/docs/ja-jp/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce)を使用して、`auth0_flutter` SDK で Flutter の Windows デスクトップアプリにログイン、ログアウト、ユーザープロファイルの表示を追加する方法を説明します。

## はじめる

**1. Flutter の Windows プロジェクトを作成する**

Windows プラットフォーム対応の新しい Flutter プロジェクトを作成します。

```shellscript theme={null}
flutter create --platforms=windows my_app
cd my_app
```

Windows が利用可能か確認します:

```shellscript theme={null}
flutter devices
```

Windows デスクトップ デバイスが一覧に表示されるはずです。

> [!TIP]
>
> `flutter doctor` を実行して、環境が正しく設定されており、C++ によるデスクトップ開発を含む Visual Studio 2022 が検出されていることを確認します。

**2. Auth0 Flutter SDKをインストールする**

Windows をサポートする SDK のベータ版を追加します:

```shellscript theme={null}
flutter pub add auth0_flutter:2.1.0-beta.1
flutter pub add flutter_dotenv
```

`pubspec.yaml` には次の内容を含めてください。

```yaml pubspec.yaml theme={null}
dependencies:
  auth0_flutter: 2.1.0-beta.1
  flutter_dotenv: ^5.1.0
```

> [!TIP]
>
> Auth0 Flutter SDK には **Flutter 3.24.0+** と **Dart 3.5.0+** が必要です。また、Windows プラットフォームでは、**Visual Studio 2022** に加えて C++ によるデスクトップ開発ワークロードも必要です。

**3. Auth0を設定する**

Windows デスクトップでの認証に必要なコールバック URL を設定して、Auth0 アプリケーションを作成または設定します。

> [tab] クイック設定
>
> Auth0 Dashboard で、次の設定を使用して **Native** アプリケーションを作成します。
>
> | 項目 | 値 |
> | - | - |
> | Allowed Callback URLs | `auth0flutter://callback` |
> | Allowed Logout URLs | `auth0flutter://callback` |
>
> 資格情報:
>
> * **Domain:** `{yourDomain}`
> * **Client ID:** `{yourClientId}`

> [tab] CLI
>
> ```shellscript theme={null}
> auth0 apps create \
>   --name "My Flutter Windows App" \
>   --type native \
>   --callbacks "auth0flutter://callback" \
>   --logout-urls "auth0flutter://callback"
> ```

> [tab] Auth0 Dashboard
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/) に移動し、**アプリケーション > アプリケーション** を選択します。
> 2. **Create Application** を選択します。
> 3. 名前を "My Flutter Windows App" にし、アプリケーションの種類として **Native** を選択します。
> 4. 新しいアプリケーションの **設定** タブを開きます。
> 5. **Allowed Callback URLs** に `auth0flutter://callback` を設定します。
> 6. **Allowed Logout URLs** に `auth0flutter://callback` を設定します。
> 7. 下にスクロールして **変更を保存** をクリックします。
> 8. Application Settings の上部にある **Domain** と **Client ID** の値をコピーします。

> [!NOTE]
>
> `auth0flutter://callback` URL は、認証の完了後にブラウザーのコールバックをデスクトップアプリケーションへ戻すためのカスタムスキームです。

**4. 環境変数を設定する**

プロジェクトのルートに `.env` ファイルを作成します。

`pubspec.yaml` で `.env` ファイルを Flutter のassetsに追加します。

```yaml pubspec.yaml theme={null}
flutter:
  assets:
    - .env
```

> [!WARNING]
>
> `.env` ファイルは絶対にバージョン管理にコミットしないでください。`.gitignore` に追加してください。

**5. Windows runner を設定する**

Windows Authenticationフローでは、アプリの runner でコールバックを受け渡す処理が必要です。Flutterプラグインは、OS からのプロトコルスキームによる起動を自動では受け取らないため、単一インスタンスの制御と URI の転送を追加する必要があります。

`windows/runner/main.cpp` の内容を次のように置き換えます。

```cpp windows/runner/main.cpp expandable lines theme={null}
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>

#include <iostream>
#include <string>
#include <thread>

#include "flutter_window.h"
#include "utils.h"

// --- Auth0 の単一インスタンス制御とコールバック処理 ---
static const wchar_t* kMutexName = L"auth0flutter_single_instance_mutex";
static const wchar_t* kPipeName = L"\\\\.\\pipe\\auth0flutter_pipe";
static const wchar_t* kCallbackPrefix = L"auth0flutter://callback";

// 名前付きパイプ経由で、実行中のインスタンスに URI を転送する
bool ForwardUriToRunningInstance(const std::wstring& uri) {
  HANDLE hPipe = CreateFileW(kPipeName, GENERIC_WRITE, 0, NULL,
                             OPEN_EXISTING, 0, NULL);
  if (hPipe == INVALID_HANDLE_VALUE) return false;

  DWORD bytesWritten;
  WriteFile(hPipe, uri.c_str(), (DWORD)(uri.size() * sizeof(wchar_t)),
           &bytesWritten, NULL);
  CloseHandle(hPipe);
  return true;
}

// 転送された URI を受信するパイプサーバースレッドを開始する
void StartPipeServer() {
  std::thread([]() {
    while (true) {
      HANDLE hPipe = CreateNamedPipeW(
          kPipeName, PIPE_ACCESS_INBOUND,
          PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
          1, 4096, 4096, 0, NULL);

      if (hPipe == INVALID_HANDLE_VALUE) break;

      if (ConnectNamedPipe(hPipe, NULL) ||
          GetLastError() == ERROR_PIPE_CONNECTED) {
        wchar_t buffer[2048] = {};
        DWORD bytesRead;
        if (ReadFile(hPipe, buffer, sizeof(buffer) - sizeof(wchar_t),
                     &bytesRead, NULL)) {
          std::wstring uri(buffer);
          if (uri.find(kCallbackPrefix) == 0) {
            SetEnvironmentVariableW(L"PLUGIN_STARTUP_URL", uri.c_str());
          }
        }
      }
      DisconnectNamedPipe(hPipe);
      CloseHandle(hPipe);
    }
  }).detach();
}

int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
                      _In_ wchar_t* command_line, _In_ int show_command) {
  // 単一インスタンスを強制する
  HANDLE hMutex = CreateMutexW(NULL, TRUE, kMutexName);
  bool alreadyRunning = (hMutex && GetLastError() == ERROR_ALREADY_EXISTS);

  // コールバック URI 付きで起動されたか確認する
  int argc;
  LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
  std::wstring startupUri;
  if (argc > 1) {
    std::wstring arg(argv[1]);
    if (arg.find(kCallbackPrefix) == 0) {
      startupUri = arg;
    }
  }
  LocalFree(argv);

  // 別のインスタンスが実行中の場合は、URI を転送して終了する
  if (alreadyRunning) {
    if (!startupUri.empty()) {
      ForwardUriToRunningInstance(startupUri);
    }
    ReleaseMutex(hMutex);
    CloseHandle(hMutex);
    return 0;
  }

  // プラグインが読み取れるよう、起動時の URI を環境変数に設定する
  if (!startupUri.empty()) {
    SetEnvironmentVariableW(L"PLUGIN_STARTUP_URL", startupUri.c_str());
  }

  // 2 回目以降に起動されたインスタンスから URI を受信するため、パイプサーバーを開始する
  StartPipeServer();

  // --- 標準の Flutter 初期化 ---
  ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);

  flutter::DartProject project;
  std::vector<std::string> command_line_arguments =
      GetCommandLineArguments();
  project.set_dart_entrypoint_arguments(
      std::move(command_line_arguments));

  FlutterWindow window(project);
  Win32Window::Point origin(10, 10);
  Win32Window::Size size(1280, 720);
  if (!window.Create(L"My App", origin, size)) {
    return EXIT_FAILURE;
  }
  window.SetQuitOnClose(true);

  ::MSG msg;
  while (::GetMessage(&msg, nullptr, 0, 0)) {
    ::TranslateMessage(&msg);
    ::DispatchMessage(&msg);
  }

  ::CoUninitialize();
  ReleaseMutex(hMutex);
  CloseHandle(hMutex);
  return EXIT_SUCCESS;
}
```

このコードでは、次のことを行います。

* Windows の mutex を使って単一インスタンスを強制します。
* コマンドライン引数として渡された `auth0flutter://callback` URI を取得します。
* 2 回目以降の起動で渡された URI を、名前付きパイプ経由で実行中のインスタンスに転送します。
* Auth0プラグインが読み取れるように、`PLUGIN_STARTUP_URL` 環境変数を設定します。

**6. カスタムURLスキームを登録する**

Windows でコールバック URI がアプリにルーティングされるよう、`auth0flutter` をカスタム URL スキームとして登録します。

`windows/url_scheme.reg` ファイルを作成します。

```reg windows/url_scheme.reg theme={null}
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\auth0flutter]
@="URL:Auth0 Flutter Protocol"
"URL Protocol"=""

[HKEY_CURRENT_USER\Software\Classes\auth0flutter\shell]

[HKEY_CURRENT_USER\Software\Classes\auth0flutter\shell\open]

[HKEY_CURRENT_USER\Software\Classes\auth0flutter\shell\open\command]
@="\"C:\\path\\to\\your\\app.exe\" \"%1\""
```

`C:\path\to\your\app.exe` は、ビルドした実際の実行可能ファイルのパスに置き換えてください。開発中は通常、次の場所になります。

```text theme={null}
build\windows\x64\runner\Debug\my_app.exe
```

`.reg` ファイルをダブルクリックして、Windows レジストリにインポートします。

> [!NOTE]
>
> 本番環境向けに配布する場合は、`.reg` ファイルに頼るのではなく、アプリのインストーラー (MSIX、Inno Setup など) でカスタム URL スキームをプログラムから登録してください。

**スキームが正しく機能することを確認します。**

コマンド プロンプトを開き、次を実行します。

```shellscript theme={null}
start auth0flutter://test
```

アプリが起動するか、すでに起動している場合は前面に表示されます。

**7. Implementでのログインとログアウト**

Windows Authentication を処理する `lib/auth_service.dart` を作成します。

```dart lib/auth_service.dart theme={null}
import 'package:auth0_flutter/auth0_flutter.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

class AuthService {
  late final Auth0 _auth0;
  Credentials? _credentials;

  AuthService() {
    _auth0 = Auth0(
      dotenv.env['AUTH0_DOMAIN']!,    // アプリケーション設定 → Domain から取得
      dotenv.env['AUTH0_CLIENT_ID']!, // アプリケーション設定 → Client ID から取得
    );
  }

  Credentials? get credentials => _credentials;
  bool get isAuthenticated => _credentials != null;

  Future<void> login() async {
    final result = await _auth0.windowsWebAuthentication().login(
      appCustomURL: 'auth0flutter://callback', // 登録済みのスキームと一致する必要があります
      authTimeout: const Duration(minutes: 5),
    );
    _credentials = result;
  }

  Future<void> logout() async {
    await _auth0.windowsWebAuthentication().logout(
      appCustomURL: 'auth0flutter://callback',
    );
    _credentials = null;
  }
}
```

> [!NOTE]
>
> Auth0 Flutter Windows SDK は現在、資格情報の管理をサポートしていません。アプリの再起動後もセッションを維持する必要がある場合は、資格情報を手動で保存する必要があります。

**8. ユーザープロファイル情報を表示**

`lib/main.dart` にメイン アプリの UI を作成します:

```dart lib/main.dart expandable lines theme={null}
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';

import 'auth_service.dart';

Future<void> main() async {
  await dotenv.load();
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Auth0 Flutter Windows',
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  final AuthService _authService = AuthService();
  bool _isLoading = false;

  Future<void> _login() async {
    setState(() => _isLoading = true);
    try {
      await _authService.login();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Login failed: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  Future<void> _logout() async {
    setState(() => _isLoading = true);
    try {
      await _authService.logout();
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('Logout failed: $e')),
        );
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final credentials = _authService.credentials;

    return Scaffold(
      appBar: AppBar(title: const Text('Auth0 Flutter Windows')),
      body: Center(
        child: _isLoading
            ? const CircularProgressIndicator()
            : credentials == null
                ? ElevatedButton(
                    onPressed: _login,
                    child: const Text('Log In'),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      if (credentials.user.pictureUrl != null)
                        CircleAvatar(
                          backgroundImage: NetworkImage(
                            credentials.user.pictureUrl!.toString(),
                          ),
                          radius: 40,
                        ),
                      const SizedBox(height: 16),
                      Text(
                        credentials.user.name ?? 'Unknown',
                        style: Theme.of(context).textTheme.headlineSmall,
                      ),
                      Text(credentials.user.email ?? ''),
                      const SizedBox(height: 24),
                      ElevatedButton(
                        onPressed: _logout,
                        child: const Text('Log Out'),
                      ),
                    ],
                  ),
      ),
    );
  }
}
```

**9. アプリケーションを起動する**

アプリをビルドして実行します：

```shellscript theme={null}
flutter run -d windows
```

**想定されるフロー:**

1. アプリが起動し、**ログイン** ボタンが表示されます。
2. **ログイン** を選択します。システムブラウザーで Auth0 Universal Login ページが開きます。
3. ブラウザーで認証を完了します。
4. ブラウザーが `auth0flutter://callback` にリダイレクトし、アプリがフォアグラウンドに戻ります。
5. ユーザーの名前、メールアドレス、プロフィール画像が表示されます。

> [!WARNING]
>
> テストの前に、カスタム URL スキームが登録されていること (手順 6) を確認してください。登録されていないと、ブラウザーのコールバックがアプリケーションに戻りません。

> [!TIP]
>
> **チェックポイント**
>
> これで、Flutter Windows アプリケーションで Auth0 のログイン機能が完全に動作するようになっているはずです。アプリは Auth0 Universal Login のためにシステムブラウザーを開き、カスタム URL スキーム経由でコールバックを受け取り、認証されたユーザーのプロファイルを表示します。

***

## トラブルシューティングと高度な使い方

> [accordion] よくある問題と解決策
>
> ### ブラウザーは開くが、アプリがコールバックを受信しない
>
> **症状**: ブラウザーでの Auth0 login は成功するものの、アプリが資格情報を受け取りません。
>
> **対処法:**
>
> 1. レジストリ エディターを開き、`HKEY_CURRENT_USER\Software\Classes\auth0flutter\shell\open\command` で `.exe` へのパスが正しいことを確認します。
> 2. コマンド プロンプトで `start auth0flutter://test` を実行してテストします。アプリが起動するはずです。
> 3. `windows/runner/main.cpp` にパイプ サーバーとミューテックスのコードが含まれていることを確認します。
> 4. タスク マネージャーで古いインスタンスが残っていないことを確認します。
> 5. `flutter clean && flutter run -d windows` を実行して、完全に再ビルドします。
>
> ### 5 分後に認証がタイムアウトする
>
> **症状**: Login が止まったように見え、最終的に失敗します。
>
> **対処法:** アプリがコールバック URI を受信できていません。次を確認してください:
>
> 1. レジストリ エントリが正しい実行ファイル パスを指していること。
> 2. `main.cpp` 内のミューテックス名 `auth0flutter_single_instance_mutex` が統一されていること。
> 3. ファイアウォールまたはアンチウイルスが名前付きパイプをブロックしていないこと。
> 4. 古いインスタンスをすべて終了し、再ビルドすること。
>
> ### URI を転送せずに 2 つ目のアプリ インスタンスが起動する
>
> **症状**: 既存のアプリがコールバックを受信する代わりに、新しいウィンドウが開きます。
>
> **対処法:**
>
> 1. タスク マネージャーで実行中のインスタンスをすべて終了します。
> 2. `main.cpp` 内のミューテックス名が統一されていることを確認します。
> 3. 次のコマンドで再ビルドします: `flutter clean && flutter run -d windows`。
>
> ### WindowsWebAuthentication が見つからない
>
> **症状**: `windowsWebAuthentication` を参照するコンパイル エラーが発生します。
>
> **対処法:** `pubspec.yaml` で Beta 版が指定されていることを確認してください:
>
> ```yaml theme={null}
> dependencies:
>   auth0_flutter: 2.1.0-beta.1
> ```
>
> 更新するには `flutter pub get` を実行します。
>
> ### Callback URL の不一致エラー
>
> **症状**: Auth0 から "redirect\_uri\_mismatch" エラーが返されます。
>
> **対処法:**
>
> 1. [Auth0 Dashboard](https://manage.auth0.com/) → Application Settings の **Allowed Callback URLs** が正確に `auth0flutter://callback` になっていることを確認します。
> 2. コード内の `appCustomURL` パラメーターが `'auth0flutter://callback'` と一致していることを確認します。
> 3. 末尾のスラッシュや空白が入っていないか確認します。

> [accordion] 中継サーバーを使用する
>
> Auth0 がカスタム スキームに直接リダイレクトすると、ブラウザーにプロンプトが表示されたり、空白のタブが残ったりすることがあります。よりスムーズに利用するには、中継用の HTTPS サーバーを使用してください:
>
> 1. `auth0flutter://callback?code=...&state=...` にリダイレクトするサーバー endpoint (例: `https://your-app.example.com/callback`) を設定します。
> 2. [Auth0 Dashboard](https://manage.auth0.com/) → Application Settings で、**Allowed Callback URLs** を `https://your-app.example.com/callback` に設定します。
> 3. login メソッドに両方の URL を渡します:
>
> ```dart theme={null}
> final result = await auth0.windowsWebAuthentication().login(
>   appCustomURL: 'auth0flutter://callback',
>   redirectUrl: 'https://your-app.example.com/callback',
> );
> ```
>
> サーバー ページには "Redirecting..." と表示し、自動的に閉じるようにすると、よりすっきりした体験になります。

> [accordion] カスタム スコープと audience
>
> 追加のスコープや API の audience をリクエストします:
>
> ```dart theme={null}
> final result = await auth0.windowsWebAuthentication().login(
>   appCustomURL: 'auth0flutter://callback',
>   scopes: {'openid', 'profile', 'email', 'read:messages'},
>   audience: 'https://your-api.example.com',
> );
> ```
>
> `audience` パラメーターを使用する前に、[Auth0 Dashboard](https://manage.auth0.com/) → **Applications > APIs** で API を設定してください。

***

## 次のステップ

* [Auth0 Flutter SDK on GitHub](https://github.com/auth0/auth0-flutter) — ソースコードと Issue トラッカー。
* [Auth0 Flutter SDK on pub.dev](https://pub.dev/packages/auth0_flutter) — API リファレンス。
* [Flutter quickstart (Android, iOS, macOS, Web)](/docs/docs/ja-jp/quickstart/native/flutter) — 他のプラットフォーム向けガイド。
* [Token Storage Best Practices](/docs/docs/ja-jp/secure/security-guidance/data-security/token-storage) — 認証情報の安全な管理。
* [Auth0 Universal Login](/docs/docs/ja-jp/authenticate/login/auth0-universal-login) — ログイン体験をカスタマイズ。
