More
Complete Guide to Third-Party Authentication in Flutter with Parse on Back4App
43 min
introduction integrating third party authentication methods like facebook, google, and apple into your flutter app can significantly enhance user experience by providing flexible and convenient login options parse server, powered by back4app, offers built in support for these authentication providers in this tutorial, you will learn how to implement third party authentication in your flutter app using the parse sdk on back4app by the end of this tutorial, you will have a flutter app with fully functional signup and login features that include standard email/password authentication using parse third party authentication methods facebook google apple prerequisites to follow along with this tutorial, you'll need the following a back4app account sign up for a free account at back4app https //www back4app com a flutter development environment installed on your machine follow this guide https //flutter dev/docs/get started/install if you need help setting up flutter basic knowledge of flutter and dart if you're new, check out flutter's introduction https //flutter dev/docs/get started/codelab developer accounts for facebook, google, and apple (required for setting up third party login methods) an ide or text editor such as visual studio code or android studio step 1 – setting up your back4app backend 1 1 create a back4app project log in to your back4app dashboard https //dashboard back4app com/ click on "create new app" enter a name for your application, e g , "authdemo" , and click "create" once the project is created, navigate to app settings > security & keys note down your application id and client key you'll need these values to initialize parse in your flutter app 1 2 enable authentication providers in your back4app dashboard, navigate to server settings > authentication enable the authentication methods you intend to use facebook google apple for each provider, you will need to input specific credentials (app ids, client ids, secrets, etc ), which will be set up in the upcoming steps step 2 – installing and setting up parse sdk in flutter 2 1 create a new flutter project open your terminal and create a new flutter project flutter create auth demo cd auth demo 2 2 add dependencies open pubspec yaml and add the following dependencies for parse and third party sign in options 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 run flutter pub get to install the dependencies 2 3 initialize parse in main dart in the lib/main dart file, import the parse sdk and initialize it in the main function 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(), ); } } replace 'your app id' and 'your client key' with your actual back4app credentials from step 1 step 3 – implementing standard authentication 3 1 create the authentication service create a new directory called services under lib and add a file named auth service dart this service will handle user registration and login using 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 create the authentication screen create a new directory called screens under lib and add a file named auth screen dart this screen will provide the ui for standard authentication // 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 ], ), ), ), ); } } step 4 – integrating facebook authentication 4 1 set up facebook developer account create a facebook app go to facebook for developers https //developers facebook com/ and log in click on "my apps" and then "create app" select "consumer" as the app type and click "next" fill in the app name and contact email , then click "create app" add facebook login to your app in your app dashboard, navigate to "add a product" and select "facebook login" choose "android" and/or "ios" depending on your target platform follow the setup steps provided by facebook you will need your app's bundle identifier for ios and package name for android configure oauth redirect uri set the oauth redirect uri to https //parseapi back4app com/auth/facebook/callback obtain app id and app secret in your app dashboard, go to "settings" > "basic" note down the app id and app secret add app id and secret to back4app in back4app dashboard, navigate to server settings > authentication under facebook , input your app id and app secret 4 2 update auth service dart with facebook login add the following code to handle facebook authentication // 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 add facebook login button to auth screen dart add the following button to your 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 platform specific configurations android update your 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> add your facebook app id to 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 update your info plist file \<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> step 5 – integrating google authentication 5 1 set up google developer account create a project in google cloud console go to google cloud console https //console cloud google com/ and create a new project configure oauth consent screen navigate to apis & services > oauth consent screen set up the consent screen with necessary scopes create oauth client id go to credentials > create credentials > oauth client id choose web application add authorized redirect uris https //parseapi back4app com/auth/google/callback note down the client id and client secret add client id and secret to back4app in back4app dashboard, under server settings > authentication , input your client id and client secret for google 5 2 update auth service dart with google login add the following code to handle google authentication // 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 add google login button to auth screen dart add the following button to your 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 platform specific configurations android add the following to your android/app/build gradle file dependencies { // add this line implementation 'com google android gms\ play services auth 20 0 0' // existing dependencies } add your google client id to 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> update your 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 add the reversed client id to your info plist \<key>cfbundleurltypes\</key> \<array> \<dict> \<key>cfbundleurlschemes\</key> \<array> \<string>com googleusercontent apps your client id\</string> \</array> \</dict> \</array> step 6 – integrating apple authentication 6 1 set up apple developer account register your app sign in to apple developer portal https //developer apple com/ and register your app enable sign in with apple under identifiers , select your app and enable sign in with apple create a services id create a services id for your app set the redirect uri to https //parseapi back4app com/auth/apple/callback generate a client secret create a sign in with apple private key use this key to generate a client secret add credentials to back4app in back4app dashboard, under server settings > authentication , input your services id and client secret for apple 6 2 update auth service dart with apple login add the following code to handle apple authentication // 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 add apple login button to auth screen dart add the following button to your 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 platform specific configurations ios only in xcode, open your project and go to signing & capabilities click on "+ capability" and add "sign in with apple" ensure that your bundle identifier matches the one registered on the apple developer portal step 7 – testing your application now that you've set up all authentication methods, you can run your app and test each login option 7 1 run the app flutter run for ios, you must run the app on a real device to test sign in with apple for android, you can use an emulator or a physical device 7 2 test standard authentication enter a username, email, and password tap "sign up" to create a new user tap "login" to log in with the created credentials 7 3 test facebook login tap "login with facebook" a facebook login screen will appear log in with your facebook credentials 7 4 test google login tap "login with google" a google sign in screen will appear log in with your google account 7 5 test apple login (ios only) tap "login with apple" the apple sign in prompt will appear authenticate using your apple id conclusion in this tutorial, you successfully implemented standard email/password authentication and integrated third party authentication methods (facebook, google, and apple) into your flutter app using the parse sdk on back4app this setup enhances user experience by offering multiple convenient login options next steps user profiles extend the app to manage user profiles, allowing users to update their information logout functionality implement logout features for each authentication method data security secure your data by implementing role based access control with parse acls and roles error handling improve error handling to provide more detailed feedback to users ui enhancements customize the ui to match your app's branding and improve user experience additional resources back4app documentation https //www back4app com/docs parse flutter sdk guide https //docs parseplatform org/flutter/guide/ flutter official documentation https //flutter dev/docs facebook for developers https //developers facebook com/ google identity platform https //developers google com/identity sign in with apple documentation https //developer apple com/sign in with apple/ happy coding!