Flutter Sign In with Apple on Parse
Introduction
Parse Server supports 3rd party authentication.
In this guide, you will learn how to support Sign In with Apple to your Flutter app on Parse.
Prerequisites
To complete this tutorial, you will need:
- Flutter version 2.2.x or later
- Android Studio or VS Code installed (with Plugins Dart and Flutter)
- A Flutter app created and connected to Back4app.
- Note: Follow the Install Parse SDK on Flutter project to create an Flutter Project connected to Back4App.
- Paid membership to the Apple Developer Program.
- Set up the plugin
sign_in_with_apple
on project.- A device (not Simulator) running iOS.
Goal
Sign in with Apple in Flutter app on Parse Server
Step 1 - Add the Sign In with Apple capability to your iOS base project
- Open
ios/Runner.xcworkspace
in Xcode - Check the plugin
sign_in_with_apple
instructions for setting upSign in with Apple
in your iOS project - Select
Team
for project - Save e close Xcode
Step 2 - Configure App ID in Developer Portal
Log into your Apple Developer account and go to the Identifiers
section.
Check if your created Bundle Identifier
is there
Click the Bundle Identifier
and scroll down. Check if the Sign In with Apple
is selected
Click Edit
and make sure the Enable as a primary App ID
is selected
If everything is right, save and exit.
Step 3 - Set up Parse Auth for Apple
Go to Back4App website, log in and then find your app. After that, click on Server Settings
and search for the Apple Login
block and select Settings
.
The Apple Login
section looks like this:
Now, you just need to paste your Bundle ID
in the field below and click on the button to save.
In case you face any trouble while integrating Apple Login, please contact our team via chat!
Step 4 - Add the Sign In with Apple
Now that you have the project set up, we can get the user data and sign in to Parse.
According to the documentation, we must send a Map with user authentication data.
1
2
3
4
5
6
7
8
9
10
11
12
final credential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
);
//https://docs.parseplatform.org/parse-server/guide/#apple-authdata
//According to the documentation, we must send a Map with user authentication data.
//Make sign in with Apple
final parseResponse = await ParseUser.loginWith('apple',
apple(credential.identityToken!, credential.userIdentifier!));
Step 5 - Sign in with Apple from Flutter
Let’s now use our example for Sign in with Apple in Flutter App, with a simple interface.
Open your Flutter project, go to the main.dart file, clean up all the code, and replace it with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import 'package:flutter/material.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final keyApplicationId = 'YOUR_APP_ID_HERE';
final keyClientKey = 'YOUR_CLIENT_KEY_HERE';
final keyParseServerUrl = 'https://parseapi.back4app.com';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey, debug: true);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Future<bool> hasUserLogged() async {
ParseUser? currentUser = await ParseUser.currentUser() as ParseUser?;
if (currentUser == null) {
return false;
}
//Checks whether the user's session token is valid
final ParseResponse? parseResponse =
await ParseUser.getCurrentUserFromServer(currentUser.sessionToken!);
if (parseResponse?.success == null || !parseResponse!.success) {
//Invalid session. Logout
await currentUser.logout();
return false;
} else {
return true;
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter - Sign In with Apple',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: FutureBuilder<bool>(
future: hasUserLogged(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Scaffold(
body: Center(
child: Container(
width: 100,
height: 100,
child: CircularProgressIndicator()),
),
);
default:
if (snapshot.hasData && snapshot.data!) {
return UserPage();
} else {
return HomePage();
}
}
}),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter - Sign In with Apple'),
),
body: Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
height: 200,
child: Image.network(
'http://blog.back4app.com/wp-content/uploads/2017/11/logo-b4a-1-768x175-1.png'),
),
Center(
child: const Text('Flutter on Back4App',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
),
SizedBox(
height: 100,
),
Container(
height: 50,
child: ElevatedButton(
child: const Text('Sign In with Apple'),
onPressed: () => doSignInApple(),
),
),
SizedBox(
height: 16,
),
],
),
),
));
}
void doSignInApple() async {
late ParseResponse parseResponse;
try {
//Set Scope
final credential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
);
//https://docs.parseplatform.org/parse-server/guide/#apple-authdata
//According to the documentation, we must send a Map with user authentication data.
//Make sign in with Apple
parseResponse = await ParseUser.loginWith('apple',
apple(credential.identityToken!, credential.userIdentifier!));
if (parseResponse.success) {
final ParseUser parseUser = await ParseUser.currentUser() as ParseUser;
//Additional Information in User
if (credential.email != null) {
parseUser.emailAddress = credential.email;
}
if (credential.givenName != null && credential.familyName != null) {
parseUser.set<String>(
'name', '${credential.givenName} ${credential.familyName}');
}
parseResponse = await parseUser.save();
if (parseResponse.success) {
Message.showSuccess(
context: context,
message: 'User was successfully with Sign In Apple!',
onPressed: () async {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => UserPage()),
(Route<dynamic> route) => false,
);
});
} else {
Message.showError(
context: context, message: parseResponse.error!.message);
}
} else {
Message.showError(
context: context, message: parseResponse.error!.message);
}
} on Exception catch (e) {
print(e.toString());
Message.showError(context: context, message: e.toString());
}
}
}
class UserPage extends StatelessWidget {
Future<ParseUser?> getUser() async {
return await ParseUser.currentUser() as ParseUser?;
}
@override
Widget build(BuildContext context) {
void doUserLogout() async {
final currentUser = await ParseUser.currentUser() as ParseUser;
var response = await currentUser.logout();
if (response.success) {
Message.showSuccess(
context: context,
message: 'User was successfully logout!',
onPressed: () {
Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (context) => HomePage()),
(Route<dynamic> route) => false,
);
});
} else {
Message.showError(context: context, message: response.error!.message);
}
}
return Scaffold(
appBar: AppBar(
title: Text('Flutter - Sign In with Apple'),
),
body: FutureBuilder<ParseUser?>(
future: getUser(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(
child: Container(
width: 100,
height: 100,
child: CircularProgressIndicator()),
);
default:
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Text(
'Hello, ${snapshot.data!.get<String>('name')}')),
SizedBox(
height: 16,
),
Container(
height: 50,
child: ElevatedButton(
child: const Text('Logout'),
onPressed: () => doUserLogout(),
),
),
],
),
);
}
}));
}
}
class Message {
static void showSuccess(
{required BuildContext context,
required String message,
VoidCallback? onPressed}) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success!"),
content: Text(message),
actions: <Widget>[
new ElevatedButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
if (onPressed != null) {
onPressed();
}
},
),
],
);
},
);
}
static void showError(
{required BuildContext context,
required String message,
VoidCallback? onPressed}) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Error!"),
content: Text(message),
actions: <Widget>[
new ElevatedButton(
child: const Text("OK"),
onPressed: () {
Navigator.of(context).pop();
if (onPressed != null) {
onPressed();
}
},
),
],
);
},
);
}
}
Find your Application Id and Client Key credentials navigating to your app Dashboard at Back4App Website.
Update your code in main.dart
with the values of your project’s ApplicationId and ClientKey in Back4app.
- keyApplicationId =
App Id
- keyClientKey =
Client Key
Run the project, and the app will load as shown in the image.
Conclusion
At this stage, you are able to use Sign in with Apple in Flutter on Back4app.