Auth0.swift

Overview

Auth0をアプリにシームレスに統合できる、iOS・macOS・tvOS・watchOS向けのSwift SDKです。ログインとログアウトを追加し、資格情報を安全に保管して、ユーザー情報にアクセスすることができます。

参照GitHubリポジトリ

v1からの移行:移行ガイドを参照してください

ドキュメント

使用を開始する

要件

  • iOS 13.0+ / macOS 11.0+ / tvOS 13.0+ / watchOS 7.0+

  • Xcode 14.x

  • Swift 5.7+

インストール

Swift Package Manager

Xcodeで以下のメニュー項目を開きます:

[File(ファイル)] > [Add Packages...(パッケージの追加)]

[Search or Enter Package URL(パッケージURLを検索または入力)]検索ボックスに次のURLを入力します。

https://github.com/auth0/Auth0.swift

Was this helpful?

/

次に、依存ルールを選択して[Add Package(パッケージを追加)]を押します。

Cocoapods

以下のラインをPodfileに追加します。

pod 'Auth0', '~> 2.0'

Was this helpful?

/

それからpod installを実行します。

Carthage

以下のラインをCartfileに追加します。

github "auth0/Auth0.swift" ~> 2.0

Was this helpful?

/

それからcarthage bootstrap --use-xcframeworksを実行します。

SDKを構成する

Auth0 Dashboardに移動し、新しい[Native(ネイティブ)]アプリケーションを作成します。

Auth0.swiftはAuth0と通信するためにAuth0アプリケーションのClient ID(クライアントID)][Domain(ドメイン)]を必要とします。これらの詳細はAuth0アプリケーションの設定ページで確認できますカスタムドメインを使用している場合は、設定ページの値ではなく、カスタムドメインの値を使用してください。

クライアントIDとドメインをplistで設定する

Auth0.plistという名前の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>{yourAuth0ClientId}</string>
    <key>Domain</key>
    <string>{yourAuth0Domain}</string>
</dict>
</plist>

Was this helpful?

/

クライアントIDとドメインをプログラムで設定する

Web Authの場合

Auth0
    .webAuth(clientId: "{yourAuth0ClientID}", domain: "{yourAuth0Domain}")
    // ...

Was this helpful?

/

Authentication APIクライアントの場合

Auth0
    .authentication(clientId: "{yourAuth0ClientID}", domain: "{yourAuth0Domain}")
    // ...

Was this helpful?

/

Management APIクライアント(ユーザー)の場合

Auth0
    .users(token: credentials.accessToken, domain: "{yourAuth0Domain}")
    // ...

Was this helpful?

/

Web Authを設定する(iOS/macOS)

コールバックURLとログアウトURLを設定する

コールバックURLとログアウトURLは、Auth0がアプリケーションにリダイレクトするために呼び出すURLです。Auth0は、ユーザー認証後にコールバックURLを呼び出し、セッションCookieを削除した後にログアウトURLを呼び出します。

コールバックURLとログアウトURLは操作できるため、Auth0アプリケーションの設定ページにある[Allowed Callback URLs(許可されているコールバックURL)][Allowed Logout URLs(許可されているログアウトURL)]のフィールドに使用するURLを追加する必要があります。これにより、Auth0はこれらのURLを有効なものと認識できるようになります。コールバックURLとログアウトURLを設定しないと、ユーザーはアプリケーションへのログインやログアウトが行えなくなり、エラーが発生します。

Auth0アプリケーションの設定ページを開き、アプリケーションのプラットフォームに応じて、対応するURLを[Allowed Callback URLs(許可されているコールバックURL)][Allowed Logout URLs(許可されているログアウトURL)]に追加します。カスタムドメインを使用している場合は、設定ページの値ではなく、{yourAuth0Domain}をカスタムドメインの値に置き換えてください。

iOS

{yourBundleIdentifier}://{yourAuth0Domain}/ios/{yourBundleIdentifier}/callback

Was this helpful?

/

macOS

{yourBundleIdentifier}://{yourAuth0Domain}/macos/{yourBundleIdentifier}/callback

Was this helpful?

/

たとえば、iOSのバンドル識別子がcom.example.MyAppでAuth0ドメインがexample.us.auth0.comの場合には、次の値になります。

com.example.MyApp://example.us.auth0.com/ios/com.example.MyApp/callback

Was this helpful?

/

カスタムURLスキームを設定する

Xcodeで、アプリターゲット設定の[Info(情報)]タブを開きます。[URL Types(URLタイプ)]セクションでボタンをクリックして、新しいエントリを追加します。そこで、[Identifier(識別子)]フィールドにauth0と入力し、[URL Schemes(URLスキーム)]フィールドに$(PRODUCT_BUNDLE_IDENTIFIER)と入力します。

これにより、バンドル識別子がカスタムURLスキームとして登録され、コールバックURLとログアウトURLがアプリに到達できるようになります。

Web Authのログイン(iOS/macOS)

ログインページを提示したいファイルにAuth0モジュールをインポートします。

import Auth0

Was this helpful?

/

それから[Login(ログイン)]ボタンのアクションでユニバーサルログインページを提示します。

Auth0
    .webAuth()
    .start { result in
        switch result {
        case .success(let credentials):
            print("Obtained credentials: \(credentials)")
        case .failure(let error):
            print("Failed with: \(error)")
        }
    }

Was this helpful?

/

async/awaitを使用する

do {
    let credentials = try await Auth0.webAuth().start()
    print("Obtained credentials: \(credentials)")
} catch {
    print("Failed with: \(error)")
}

Was this helpful?

/

Combineを使用する

Auth0
    .webAuth()
    .start()
    .sink(receiveCompletion: { completion in
        if case .failure(let error) = completion {
            print("Failed with: \(error)")
        }
    }, receiveValue: { credentials in
        print("Obtained credentials: \(credentials)")
    })
    .store(in: &cancellables)

Was this helpful?

/

Web Authのログアウト(iOS/macOS)

ユーザーをログアウトさせるには、ユニバーサルログインセッションのCookieをクリアし、アプリケーションからユーザーの資格情報を削除します。

[Logout(ログアウト)]ボタンのアクションでclearSession()メソッドを呼び出します。セッションCookieがクリアされたら、ユーザーの資格情報を削除します

Auth0
    .webAuth()
    .clearSession { result in
        switch result {
        case .success:
            print("Session cookie cleared")
            // Delete credentials
        case .failure(let error):
            print("Failed with: \(error)")
        }
    }

Was this helpful?

/

async/awaitを使用する

do {
    try await Auth0.webAuth().clearSession()
    print("Session cookie cleared")
    // Delete credentials
} catch {
    print("Failed with: \(error)")
}

Was this helpful?

/

Combineを使用する

Auth0
    .webAuth()
    .clearSession()
    .sink(receiveCompletion: { completion in
        switch completion {
        case .finished:
            print("Session cookie cleared")
            // Delete credentials
        case .failure(let error):
            print("Failed with: \(error)")
        }
    }, receiveValue: {})
    .store(in: &cancellables)

Was this helpful?

/

SSOアラートボックス(iOS/macOS)

undefined

Web Authを使用しているときにデフォルトで表示されるアラートボックスの詳細については、FAQを参照してください。

次の手順

ほとんどの機能については、で説明されています。