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

AI を使って Auth0 を統合する

Claude Code、Cursor、GitHub Copilot などの AI コーディングアシスタントを使えば、agent skills を利用して数分で Auth0 認証を自動追加できます。インストール:
npx skills add auth0/agent-skills --skill auth0-quickstart --skill auth0-swift
次に、AI アシスタントに次のように依頼します。
Add Auth0 authentication to my iOS app
AI アシスタントが Auth0 アプリケーションを自動的に作成し、認証情報を取得して、Auth0.swift SDK 依存関係の追加、Auth0.plist の設定、コールバック URL の設定、ログイン/ログアウトフローの実装まで行います。agent skills の完全なドキュメント →

はじめに

1

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

このクイックスタート用に、新しい iOS または macOS のプロジェクトを作成します。Xcode で:
  1. FileNewProject (または ⌘+Shift+N)
  2. 次のいずれかを選択します。
    • iOS タブ → App テンプレート
    • macOS タブ → App テンプレート
  3. プロジェクトを設定します。
    • Product Name: Auth0-Sample
    • Interface: SwiftUI
    • Language: Swift
    • Use Core Data: チェックなし
    • Include Tests: チェックあり (推奨)
  4. 保存場所を選択して Create をクリックします
これにより、SwiftUI と Swift Package Manager をサポートする標準的なアプリが作成され、Auth0 との統合に最適です。
2

Auth0 SDK を追加

お好みのパッケージマネージャーを使用して、Auth0 SDK をプロジェクトに追加します。
Xcode で:
  1. FileAdd Package Dependencies… (または ⌘+Shift+K)
  2. Auth0 SDK の URL を入力します。
    https://github.com/auth0/Auth0.swift
    
  3. Add Package → アプリのターゲットを選択 → Add Package
3

Auth0 を設定する

新しい Auth0 アプリケーションを作成し、コールバックURLを設定します。
  1. Auth0 Dashboard に移動します
  2. Applications > Create Application > 名前を入力し、Native を選択して Create をクリックします
  3. Settings タブで、クライアントIDドメイン を控えます
  4. 次のURLを Allowed Callback URLs に追加します:
https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,
YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback
  1. 次のURLを Allowed Logout URLs に追加します:
https://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback,
YOUR_BUNDLE_IDENTIFIER://{yourDomain}/ios/YOUR_BUNDLE_IDENTIFIER/callback
  1. Save Changes をクリックします
4

アプリケーションの認証情報を設定

プロジェクトディレクトリにAuth0.plistを作成します:
Auth0.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>ClientId</key>
    <string>YOUR_AUTH0_CLIENT_ID</string>
    <key>Domain</key>
    <string>{yourDomain}</string>
</dict>
</plist>
Auth0.plist を Xcode にドラッグし、“Add to target” がチェックされていることを確認します。
5

認証サービスを作成する

AuthenticationService.swift を作成します。
  1. プロジェクトを右クリック → New File…Swift File
  2. 名前を AuthenticationService にします
  3. 内容を次のように置き換えます。
AuthenticationService.swift
import Foundation
import Auth0
import Combine

@MainActor
class AuthenticationService: ObservableObject {
    @Published var isAuthenticated = false
    @Published var user: User?
    @Published var isLoading = false
    @Published var errorMessage: String?
    
    private let credentialsManager = CredentialsManager(authentication: Auth0.authentication())
    
    init() {
        Task {
            await checkAuthenticationStatus()
        }
    }
    
    private func checkAuthenticationStatus() async {
        isLoading = true
        defer { isLoading = false }
        
        guard let credentials = try? await credentialsManager.credentials() else {
            isAuthenticated = false
            return
        }
        
        isAuthenticated = true
        // IDトークンからユーザー情報を取得する
        user = credentials.user
    }
    
    func login() async {
        isLoading = true
        errorMessage = nil
        defer { isLoading = false }
        
        do {
            let credentials = try await Auth0
                .webAuth()
                .scope("openid profile email offline_access")
                .start()
            
            _ = credentialsManager.store(credentials: credentials)
            isAuthenticated = true
            // Get user info from the ID token
            user = credentials.user
        } catch {
            errorMessage = "Login failed: \(error.localizedDescription)"
        }
    }
    
    func logout() async {
        isLoading = true
        defer { isLoading = false }
        
        do {
            try await Auth0
              .webAuth()
              .clearSession()
            _ = credentialsManager.clear()
            isAuthenticated = false
            user = nil
        } catch {
            errorMessage = "Logout failed: \(error.localizedDescription)"
        }
    }
}
6

認証フローを設定する(任意)

ユーザーエクスペリエンスを向上させるために、次の方法でシステムアラートを最小限に抑えられます。
  1. Universal Links を使用する: リダイレクト中に表示される「“AppName”で開きますか?」というプロンプトが表示されなくなります。注: ASWebAuthenticationSession の権限アラートは引き続き表示されます。
  2. Ephemeral Sessions を使用する: すべての権限アラートが表示されなくなります。注: これによりシングルサインオン (SSO) と共有 Cookie は無効になります。
この手順はスキップして、権限アラートが表示されるデフォルトの動作を使用できます。これは後で設定できます。
8

アプリを実行する

Xcode で ⌘+R を押します。
  1. 「Log In」をタップ → 権限アラート (デフォルト設定を使用している場合) → 「続行」をタップ
  2. ブラウザーでログインを完了します
  3. プロファイルが表示されます
チェックポイントこれで、iOS または macOS アプリで Auth0 ログインが完全に動作するようになりました!

トラブルシューティングと詳細設定