More
Back4AppのParseを使用したFlutterのサードパーティ認証に関する完全ガイド
42 分
はじめに facebook、google、appleなどのサードパーティ認証方法をflutterアプリに統合することで、柔軟で便利なログインオプションを提供し、ユーザーエクスペリエンスを大幅に向上させることができます。back4appが提供するparse serverは、これらの認証プロバイダーに対する組み込みサポートを提供しています。このチュートリアルでは、back4appのparse sdkを使用してflutterアプリにサードパーティ認証を実装する方法を学びます。 このチュートリアルの終わりまでに、以下の機能を備えた完全に機能するサインアップおよびログイン機能を持つflutterアプリを作成することができます parseを使用した標準のメール/パスワード認証。 サードパーティ認証方法 facebook google apple 前提条件 このチュートリアルに従うには、以下が必要です back4appアカウント を作成してください。 back4app https //www back4app com で無料アカウントにサインアップします。 flutter開発環境 がマシンにインストールされていること。 このガイド https //flutter dev/docs/get started/install を参照してflutterのセットアップに関するヘルプを受けてください。 flutterとdartの基本的な知識 が必要です。もし新しい場合は、 flutterの紹介 https //flutter dev/docs/get started/codelab を確認してください。 facebook、google、appleの 開発者アカウント (サードパーティログイン方法を設定するために必要)。 visual studio codeやandroid studioなどの ideまたはテキストエディタ 。 ステップ 1 – back4app バックエンドの設定 1 1 back4app プロジェクトの作成 あなたの back4app ダッシュボード https //dashboard back4app com/ にログインします。 "新しいアプリを作成" をクリックします。 アプリケーションの名前を入力します。例 "authdemo" , そして "作成" をクリックします。 プロジェクトが作成されたら、次に進みます。 アプリ設定 > セキュリティとキー に移動します。 あなたの アプリケーション id と クライアントキー をメモしておいてください。これらの値は、flutter アプリで parse を初期化するために必要です。 1 2 認証プロバイダーの有効化 back4app ダッシュボードで、次に進みます。 サーバー設定 > 認証 に移動します。 使用する認証方法を有効にします facebook google apple 各プロバイダーについて、特定の資格情報(アプリ id、クライアント id、シークレットなど)を入力する必要があります。これらは今後のステップで設定されます。 ステップ 2 – flutter における parse sdk のインストールと設定 2 1 新しいflutterプロジェクトを作成する ターミナルを開いて、新しいflutterプロジェクトを作成します flutter create auth demo cd auth demo 2 2 依存関係を追加する pubspec yaml を開いて、parseおよびサードパーティのサインインオプションのための以下の依存関係を追加します dependencies flutter sdk flutter parse server sdk flutter ^4 0 1 flutter facebook auth ^5 0 5 google sign in ^5 4 0 sign in with apple ^3 3 0 依存関係をインストールするために、 flutter pub get を実行します。 2 3 main dart でparseを初期化する lib/main dart ファイルで、parse sdkをインポートし、 main 関数内で初期化します import 'package\ flutter/material dart'; import 'package\ parse server sdk flutter/parse server sdk dart'; import 'screens/auth screen dart'; // you'll create this file later void main() async { widgetsflutterbinding ensureinitialized(); const keyapplicationid = 'your app id'; const keyclientkey = 'your client key'; const keyparseserverurl = 'https //parseapi back4app com'; await parse() initialize( keyapplicationid, keyparseserverurl, clientkey keyclientkey, autosendsessionid true, debug true, ); runapp(myapp()); } class myapp extends statelesswidget { @override widget build(buildcontext context) { return materialapp( title 'parse auth demo', theme themedata( primaryswatch colors blue, ), home authscreen(), ); } } 'your app id' と 'your client key' を、ステップ1からの実際のback4appの資格情報に置き換えます。 ステップ3 – 標準認証の実装 3 1 認証サービスを作成する 新しいディレクトリを作成します。 services を lib の下に作成し、 auth service dart という名前のファイルを追加します。このサービスは、parseを使用してユーザー登録とログインを処理します。 // lib/services/auth service dart import 'package\ parse server sdk flutter/parse server sdk dart'; class authservice { future\<parseuser?> signup(string username, string password, string email) async { var user = parseuser(username, password, email); var response = await user signup(); if (response success) { return user; } else { return null; } } future\<parseuser?> login(string username, string password) async { var user = parseuser(username, password, null); var response = await user login(); if (response success) { return user; } else { return null; } } future\<void> logout() async { var user = await parseuser currentuser() as parseuser?; await user? logout(); } } 3 2 認証画面を作成する 新しいディレクトリを作成します。 screens を lib の下に作成し、 auth screen dart という名前のファイルを追加します。この画面は、標準的な認証のためのuiを提供します。 // lib/screens/auth screen dart import 'package\ flutter/material dart'; import ' /services/auth service dart'; class authscreen extends statefulwidget { @override authscreenstate createstate() => authscreenstate(); } class authscreenstate extends state\<authscreen> { final texteditingcontroller usernamecontroller = texteditingcontroller(); final texteditingcontroller passwordcontroller = texteditingcontroller(); final texteditingcontroller emailcontroller = texteditingcontroller(); final authservice authservice = authservice(); void signup() async { var user = await authservice signup( usernamecontroller text trim(), passwordcontroller text trim(), emailcontroller text trim(), ); if (user != null) { scaffoldmessenger of(context) showsnackbar(snackbar(content text('user created successfully!'))); } else { scaffoldmessenger of(context) showsnackbar(snackbar(content text('sign up failed '))); } } void login() async { var user = await authservice login( usernamecontroller text trim(), passwordcontroller text trim(), ); if (user != null) { scaffoldmessenger of(context) showsnackbar(snackbar(content text('login successful!'))); } else { scaffoldmessenger of(context) showsnackbar(snackbar(content text('login failed '))); } } @override widget build(buildcontext context) { return scaffold( appbar appbar(title const text('parse auth')), body padding( padding const edgeinsets all(16 0), child singlechildscrollview( child column( children \[ const text( 'standard authentication', style textstyle(fontsize 18, fontweight fontweight bold), ), textfield( controller usernamecontroller, decoration const inputdecoration(labeltext 'username'), ), textfield( controller emailcontroller, decoration const inputdecoration(labeltext 'email'), ), textfield( controller passwordcontroller, decoration const inputdecoration(labeltext 'password'), obscuretext true, ), const sizedbox(height 20), elevatedbutton( onpressed signup, child const text('sign up'), ), elevatedbutton( onpressed login, child const text('login'), ), const divider(), const sizedbox(height 20), const text( 'third party authentication', style textstyle(fontsize 18, fontweight fontweight bold), ), // buttons for third party authentication will be added here ], ), ), ), ); } } ステップ 4 – facebook 認証の統合 4 1 facebook 開発者アカウントの設定 facebookアプリを作成する: 行く facebook for developers https //developers facebook com/ にログインします。 クリックして "マイアプリ" を選択し、次に "アプリを作成" をクリックします。 選択する "コンシューマー" をアプリタイプとして選択し、クリックします "次へ" 「 アプリ名 」と 連絡先メール を入力し、次に 「アプリを作成」 をクリックします。 アプリにfacebookログインを追加する: アプリのダッシュボードで、 "製品を追加" に移動し、 "facebookログイン" を選択します。 選択する "android" および/または "ios" あなたのターゲットプラットフォームに応じて。 facebookが提供するセットアップ手順に従ってください。アプリの バンドル識別子 がios用と パッケージ名 がandroid用に必要です。 oauthリダイレクトuriを設定する: 「 oauthリダイレクトuri 」を次のように設定します https //parseapi back4app com/auth/facebook/callback アプリidとアプリシークレットを取得する: アプリのダッシュボードで、次に進んでください "設定" > "基本" 「 アプリid 」と 「 アプリシークレット 」をメモしてください。 back4appにアプリidとシークレットを追加する: back4appダッシュボードで、次に進みます サーバー設定 > 認証 「 facebook 」の下に、あなたの app id と app secret を入力してください。 4 2 更新 auth service dart facebookログインを使用して facebook認証を処理するために、次のコードを追加してください // add these imports at the top import 'package\ flutter facebook auth/flutter facebook auth dart'; // inside authservice class map\<string, dynamic> facebookauthdata( string? accesstoken, string? userid, datetime? expirationdate) { return { 'id' userid, 'access token' accesstoken, 'expiration date' expirationdate? toutc() toiso8601string(), }; } future\<parseuser?> loginwithfacebook() async { final loginresult result = await facebookauth instance login(); if (result status == loginstatus success) { final accesstoken accesstoken = result accesstoken!; var user = parseuser(null, null, null); var response = await user loginwith( 'facebook', facebookauthdata( accesstoken token, accesstoken userid, accesstoken expires, ), ); if (response success) { return user; } } return null; } 4 3 facebookログインボタンを追加する auth screen dart 次のボタンをuiに追加します elevatedbutton( onpressed () async { var user = await authservice loginwithfacebook(); if (user != null) { scaffoldmessenger of(context) showsnackbar(snackbar(content text('facebook login successful!'))); } else { scaffoldmessenger of(context) showsnackbar(snackbar(content text('facebook login failed '))); } }, child const text('login with facebook'), ), 4 4 プラットフォーム固有の設定 android あなたの android/app/src/main/androidmanifest xml \<manifest xmlns\ android="http //schemas android com/apk/res/android" package="com example auth demo"> \<! add this inside the \<application> tag > \<meta data android\ name="com facebook sdk applicationid" android\ value="@string/facebook app id"/> \<activity android\ name="com facebook facebookactivity" android\ configchanges="keyboard|keyboardhidden|screenlayout|screensize|orientation" android\ label="@string/app name" /> \<! existing configurations > \</manifest> あなたのfacebookアプリidを android/app/src/main/res/values/strings xml \<resources> \<string name="app name">authdemo\</string> \<string name="facebook app id">your facebook app id\</string> \</resources> ios あなたの info plist ファイルを更新してください \<key>cfbundleurltypes\</key> \<array> \<dict> \<key>cfbundleurlschemes\</key> \<array> \<string>fbyour facebook app id\</string> \</array> \</dict> \</array> \<key>facebookappid\</key> \<string>your facebook app id\</string> \<key>facebookdisplayname\</key> \<string>authdemo\</string> ステップ5 – google認証の統合 5 1 google開発者アカウントの設定 google cloud consoleでプロジェクトを作成する: に移動します google cloud console https //console cloud google com/ そして新しいプロジェクトを作成します。 oauth同意画面を設定する: に移動します apis & services > oauth同意画面 必要なスコープで同意画面を設定します。 oauthクライアントidを作成する: に移動します credentials > credentialsを作成 > oauthクライアントid を選択します webアプリケーション を追加します 承認済みリダイレクトuri https //parseapi back4app com/auth/google/callback をメモします クライアントid と クライアントシークレット クライアントidとシークレットをback4appに追加する: back4appダッシュボードで、 サーバー設定 > 認証 , に入力します クライアントid と クライアントシークレット をgoogle用に。 5 2 auth service dart をgoogleログインで更新する google 認証を処理するために次のコードを追加してください // add this import at the top import 'package\ google sign in/google sign in dart'; // inside authservice class map\<string, dynamic> googleauthdata(string? idtoken, string? accesstoken) { return { 'id token' idtoken, 'access token' accesstoken, }; } future\<parseuser?> loginwithgoogle() async { final googlesignin googlesignin = googlesignin( scopes \['email'], ); final googlesigninaccount? googleuser = await googlesignin signin(); if (googleuser == null) { return null; } final googlesigninauthentication googleauth = await googleuser authentication; var user = parseuser(null, null, null); var response = await user loginwith( 'google', googleauthdata( googleauth idtoken, googleauth accesstoken, ), ); if (response success) { return user; } return null; } 5 3 googleログインボタンを追加する auth screen dart 次のボタンをuiに追加します elevatedbutton( onpressed () async { var user = await authservice loginwithgoogle(); if (user != null) { scaffoldmessenger of(context) showsnackbar(snackbar(content text('google login successful!'))); } else { scaffoldmessenger of(context) showsnackbar(snackbar(content text('google login failed '))); } }, child const text('login with google'), ), 5 4 プラットフォーム固有の設定 android 次の内容を android/app/build gradle ファイルに追加してください dependencies { // add this line implementation 'com google android gms\ play services auth 20 0 0' // existing dependencies } あなたのgoogleクライアントidを android/app/src/main/res/values/strings xml \<resources> \<string name="app name">authdemo\</string> \<string name="default web client id">your google client id\</string> \</resources> あなたの android/app/src/main/androidmanifest xml \<manifest xmlns\ android="http //schemas android com/apk/res/android" package="com example auth demo"> \<! existing configurations > \<application> \<! existing configurations > \<meta data android\ name="com google android gms client application id" android\ value="@string/default web client id" /> \</application> \</manifest> ios 逆クライアントidをあなたの info plist \<key>cfbundleurltypes\</key> \<array> \<dict> \<key>cfbundleurlschemes\</key> \<array> \<string>com googleusercontent apps your client id\</string> \</array> \</dict> \</array> ステップ 6 – apple 認証の統合 6 1 apple developer アカウントの設定 アプリを登録する にサインイン apple developer portal https //developer apple com/ し、アプリを登録します。 appleでのサインインを有効にする の下で 識別子 , アプリを選択し、 appleでのサインイン を有効にします。 サービスidを作成する アプリのために サービスid を作成します。 を設定します リダイレクトuri を https //parseapi back4app com/auth/apple/callback クライアントシークレットを生成する を作成します appleでのサインイン プライベートキー。 このキーを使用して クライアントシークレット を生成します。 back4appに資格情報を追加する back4appダッシュボードで、 サーバー設定 > 認証 , あなたの サービスid と クライアントシークレット を入力します。 6 2 auth service dart をappleログインで更新する apple認証を処理するために次のコードを追加します // add this import at the top import 'package\ sign in with apple/sign in with apple dart'; import 'dart\ io' show platform; // inside authservice class map\<string, dynamic> appleauthdata(string? identitytoken, string? userid) { return { 'id' userid, 'token' identitytoken, }; } future\<parseuser?> loginwithapple() async { if (!platform isios) { // sign in with apple is only available on ios return null; } final credential = await signinwithapple getappleidcredential( scopes \[ appleidauthorizationscopes email, appleidauthorizationscopes fullname, ], ); var user = parseuser(null, null, null); var response = await user loginwith( 'apple', appleauthdata( credential identitytoken, credential useridentifier, ), ); if (response success) { return user; } return null; } 6 3 appleログインボタンを auth screen dart 次のボタンをuiに追加します elevatedbutton( onpressed () async { var user = await authservice loginwithapple(); if (user != null) { scaffoldmessenger of(context) showsnackbar(snackbar(content text('apple login successful!'))); } else { scaffoldmessenger of(context) showsnackbar(snackbar(content text('apple login failed '))); } }, child const text('login with apple'), ), 6 4 プラットフォーム固有の設定 iosのみ xcodeでプロジェクトを開き、 signing & capabilities に移動します。 "+ capability"をクリックして、 "sign in with apple" を追加します。 あなたの bundle identifier がapple developer portalに登録されているものと一致していることを確認してください。 ステップ7 – アプリケーションのテスト すべての認証方法を設定したので、アプリを実行して各ログインオプションをテストできます。 7 1 アプリを実行する flutter run iosの場合、appleでのサインインをテストするには、実際のデバイスでアプリを実行する必要があります。 androidの場合、エミュレーターまたは物理デバイスを使用できます。 7 2 標準認証のテスト ユーザー名、メールアドレス、パスワードを入力します。 新しいユーザーを作成するには、 "サインアップ" をタップします。 作成した資格情報でログインするには、 "ログイン" をタップします。 7 3 facebookログインのテスト タップ "facebookでログイン" facebookのログイン画面が表示されます。 facebookの認証情報でログインします。 7 4 googleログインのテスト タップ "googleでログイン" googleのサインイン画面が表示されます。 googleアカウントでログインします。 7 5 appleログインのテスト(iosのみ) タップ "appleでログイン" appleのサインインプロンプトが表示されます。 apple idを使用して認証します。 結論 このチュートリアルでは、標準のメール/パスワード認証を成功裏に実装し、parse sdkを使用してback4appにflutterアプリにサードパーティの認証方法(facebook、google、apple)を統合しました。この設定は、複数の便利なログインオプションを提供することでユーザーエクスペリエンスを向上させます。 次のステップ ユーザープロファイル: アプリを拡張してユーザープロファイルを管理し、ユーザーが情報を更新できるようにします。 ログアウト機能: 各認証方法のためのログアウト機能を実装します。 データセキュリティ: parse aclとロールを使用して、ロールベースのアクセス制御を実装することでデータを保護します。 エラーハンドリング: ユーザーにより詳細なフィードバックを提供するためにエラーハンドリングを改善します。 uiの強化: アプリのブランディングに合わせてuiをカスタマイズし、ユーザーエクスペリエンスを向上させます。 追加リソース back4app ドキュメント https //www back4app com/docs parse flutter sdk ガイド https //docs parseplatform org/flutter/guide/ flutter 公式ドキュメント https //flutter dev/docs facebook for developers https //developers facebook com/ google identity platform https //developers google com/identity appleでのサインイン ドキュメント https //developer apple com/sign in with apple/ コーディングを楽しんでください!