Firebase Authentication with Identity Platform にアップグレードした場合は、選択した OpenID Connect (OIDC) 準拠のプロバイダーを使用して、Firebase でユーザーを認証できます。これにより、Firebase でネイティブにサポートされていない ID プロバイダーを使用できるようになります。
あなたが始める前に
OIDC プロバイダーを使用してユーザーをサインインするには、最初にプロバイダーからいくつかの情報を収集する必要があります。
クライアント ID : アプリを識別するプロバイダー固有の文字列。プロバイダーは、サポートするプラットフォームごとに異なるクライアント ID を割り当てる場合があります。これは、プロバイダーによって発行された ID トークンの
aud
クレームの値の 1 つです。クライアント シークレット: プロバイダーがクライアント ID の所有権を確認するために使用するシークレット文字列。クライアント ID ごとに、一致するクライアント シークレットが必要になります。 (この値は、強く推奨される認証コード フローを使用している場合にのみ必要です。)
Issuer : プロバイダーを識別する文字列。この値は、
/.well-known/openid-configuration
を追加した場合にプロバイダーの OIDC ディスカバリー ドキュメントの場所となる URL である必要があります。たとえば、発行者がhttps://auth.example.com
の場合、検出ドキュメントはhttps://auth.example.com/.well-known/openid-configuration
で利用可能である必要があります。
上記の情報を入手したら、OpenID Connect を Firebase プロジェクトのサインイン プロバイダーとして有効にします。
Firebase Authentication with Identity Platform にアップグレードしていない場合は、アップグレードしてください。 OpenID Connect 認証は、アップグレードされたプロジェクトでのみ使用できます。
Firebase コンソールの [サインイン プロバイダー] ページで、[新しいプロバイダーの追加] をクリックし、[ OpenID Connect ] をクリックします。
認証コード フローを使用するか、暗黙的な付与フローを使用するかを選択します。
プロバイダーがサポートしている場合は、常にコード フローを使用する必要があります。暗黙的なフローは安全性が低く、使用しないことを強くお勧めします。
このプロバイダーに名前を付けます。生成されたプロバイダー ID に注意してください:
oidc.example-provider
ようなものです。アプリにサインイン コードを追加するときに、この ID が必要になります。クライアント ID とクライアント シークレット、およびプロバイダーの発行者文字列を指定します。これらの値は、プロバイダーが割り当てた値と正確に一致する必要があります。
変更を保存します。
Firebase SDK でログイン フローを処理する
OIDC プロバイダを使用して Firebase でユーザーを認証する最も簡単な方法は、Firebase SDK でログイン フロー全体を処理することです。
Firebase Apple プラットフォーム SDK でサインイン フローを処理するには、次の手順に従います。
カスタム URL スキームを Xcode プロジェクトに追加します。
- プロジェクト構成を開きます。左側のツリー ビューでプロジェクト名をダブルクリックします。 [ターゲット] セクションからアプリを選択し、[情報] タブを選択して、[ URL の種類] セクションを展開します。
- [ + ] ボタンをクリックし、反転したクライアント ID の URL スキームを追加します。この値を見つけるには、
構成ファイルを開き、GoogleService-Info.plist REVERSED_CLIENT_ID
キーを探します。そのキーの値をコピーして、構成ページの [ URL スキーム]ボックスに貼り付けます。他のフィールドは空白のままにします。完了すると、構成は次のようになります (ただし、アプリケーション固有の値があります)。
Firebase コンソールで取得したプロバイダー ID を使用して、
OAuthProvider
のインスタンスを作成します。迅速
var provider = OAuthProvider(providerID: "oidc.example-provider")
Objective-C
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"oidc.example-provider"];
オプション: OAuth 要求で送信する追加のカスタム OAuth パラメーターを指定します。
迅速
provider.customParameters = [ "login_hint": "user@example.com" ]
Objective-C
[provider setCustomParameters:@{@"login_hint": @"user@example.com"}];
プロバイダーがサポートするパラメーターについては、プロバイダーに確認してください。
setCustomParameters
で Firebase に必要なパラメータを渡すことはできないことに注意してください。これらのパラメータはclient_id
、response_type
、redirect_uri
、state
、scope
、およびresponse_mode
です。オプション: 基本プロファイル以外に、認証プロバイダーに要求する追加の OAuth 2.0 スコープを指定します。
迅速
provider.scopes = ["mail.read", "calendars.read"]
Objective-C
[provider setScopes:@[@"mail.read", @"calendars.read"]];
プロバイダーがサポートするスコープについては、プロバイダーに確認してください。
オプション: reCAPTCHA をユーザーに表示するときにアプリが
SFSafariViewController
またはUIWebView
を表示する方法をカスタマイズする場合は、AuthUIDelegate
プロトコルに準拠するカスタム クラスを作成します。OAuth プロバイダー オブジェクトを使用して Firebase で認証します。
迅速
// If you created a custom class that conforms to AuthUIDelegate, // pass it instead of nil: provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken } } }
Objective-C
// If you created a custom class that conforms to AuthUIDelegate, // pass it instead of nil: [provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { if (error) { // Handle error. } if (credential) { [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }]; } }];
上記の例はサインイン フローに焦点を当てていますが、 linkWithCredential を使用して
linkWithCredential
プロバイダーを既存のユーザーにリンクすることもできます。たとえば、複数のプロバイダーを同じユーザーにリンクして、いずれかでサインインできるようにすることができます。迅速
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // OIDC credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken }
Objective-C
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // OIDC credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // OAuth access token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }];
同じパターンを
reauthenticateWithCredential
で使用できます。これを使用して、最近のログインが必要な機密操作の新しい資格情報を取得できます。迅速
Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token can also be retrieved: // (authResult.credential as? OAuthCredential)?.accessToken // OAuth ID token can also be retrieved: // (authResult.credential as? OAuthCredential)?.idToken }
Objective-C
[[FIRAuth auth].currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).accessToken // OAuth ID token can also be retrieved: // ((FIROAuthCredential *)authResult.credential).idToken }];
サインイン フローを手動で処理する
アプリに OpenID Connect サインイン フローをすでに実装している場合は、ID トークンを直接使用して Firebase で認証できます。
迅速
let credential = OAuthProvider.credential(
withProviderID: "oidc.example-provider", // As registered in Firebase console.
idToken: idToken, // ID token from OpenID Connect flow.
rawNonce: nil
)
Auth.auth().signIn(with: credential) { authResult, error in
if error {
// Handle error.
return
}
// User is signed in.
// IdP data available in authResult?.additionalUserInfo?.profile
}
Objective-C
FIROAuthCredential *credential =
[FIROAuthProvider credentialWithProviderID:@"oidc.example-provider" // As registered in Firebase console.
IDToken:idToken // ID token from OpenID Connect flow.
rawNonce:nil];
[[FIRAuth auth] signInWithCredential:credential
completion:^(FIRAuthDataResult * _Nullable authResult,
NSError * _Nullable error) {
if (error != nil) {
// Handle error.
return;
}
// User is signed in.
// IdP data available in authResult.additionalUserInfo.profile
}];
次のステップ
ユーザーが初めてサインインすると、新しいユーザー アカウントが作成され、サインインに使用したユーザーの資格情報 (ユーザー名とパスワード、電話番号、または認証プロバイダー情報) にリンクされます。この新しいアカウントは Firebase プロジェクトの一部として保存され、ユーザーのサインイン方法に関係なく、プロジェクト内のすべてのアプリでユーザーを識別するために使用できます。
アプリでは、
User
オブジェクトからユーザーの基本的なプロファイル情報を取得できます。ユーザーの管理を参照してください。Firebase Realtime Database と Cloud Storageセキュリティ ルールでは、サインインしているユーザーの一意のユーザー ID を
auth
変数から取得し、それを使用してユーザーがアクセスできるデータを制御できます。
認証プロバイダーの資格情報を既存のユーザー アカウントにリンクすることで、ユーザーが複数の認証プロバイダーを使用してアプリにサインインできるようにすることができます。
ユーザーをサインアウトするには、 signOut:
を呼び出します。
迅速
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
Objective-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
認証エラーの全範囲に対してエラー処理コードを追加することもできます。エラーの処理を参照してください。