Blog / Guides
Add Sign in with Apple to a Flutter app, and test it on a real iPhone
Sign in with Apple in Flutter with Supabase, tested on a real iPhone through Zapbird. Full code, the Supabase setting that trips people up, and what to do before you ship.
Sign in with Apple is one of those features that is easy to describe and awkward to test. It only works properly on a real iPhone, it depends on settings in three different places, and the error you get when one of them is wrong does not say which. This post shows the whole path, from an empty screen to a working button, using a small chat app we built and ran on a phone with Zapbird.
Everything here is the code we actually ran. We used Supabase for the accounts, so the example is Flutter plus Supabase, but the Apple part is the same whatever backend you use. You will see the full code for the button, the one Supabase setting that decides whether it works, and what changes when you move from testing to a real release.
Why use the native flow
There are two ways to put Apple sign-in in a Flutter app. The web flow opens a browser page, signs you in there and sends you back to the app through a redirect link. The native flow shows Apple's own sheet, asks for Face ID, and hands your app a signed identity token.
We use the native flow. It is what people expect on an iPhone, it is quicker, and it does not depend on redirect links that have to be registered for your app. It is also the only one that behaves well when the app is running inside another app, which matters when you test with Zapbird, as you will see below.
There is also a rule to keep in mind. If your app offers sign-in with another company's account, such as Google, the App Store review guidelines expect you to offer Sign in with Apple, or an equivalent privacy-minded option, next to it. Check Apple's current guidelines before you submit, but plan for the button to be there.
What you need
- A Flutter project, and Zapbird running so you can try changes on your phone as you save.
- A Supabase project. The free plan is enough for this. You need the project URL and the anon key, which is meant to be public. Never put a service role key or any other secret in the app.
- An iPhone with the Zapbird runner installed and paired with your computer.
- An Apple developer account for the release step at the end. You do not need one to try the button inside the runner.
Step 1: add the packages
Add Supabase, the Apple sign-in package and a small hashing library to pubspec.yaml. The hash is used for the nonce, which we explain in step 4.
dependencies:
flutter:
sdk: flutter
supabase_flutter: ^2.18.3
sign_in_with_apple: ^8.1.0
pointycastle: ^3.9.1Run flutter pub get. If you use Zapbird, it adds an entry to zapbird.yaml when a package needs a permission, which step 7 covers. In our test all three packages worked in the runner without a store build.
Step 2: connect to Supabase
Keep the project URL and the anon key in a file that is not committed to git. We use lib/env.dart, listed in .gitignore, with an env.example.dart beside it so a new teammate knows what to fill in.
// lib/env.dart (git-ignored)
class Env {
static const supabaseUrl = 'https://YOUR-PROJECT-REF.supabase.co';
static const supabaseAnonKey = 'YOUR-ANON-KEY';
}Start Supabase before the app runs. The package saves the session on the device and restores it the next time the app starts, so people stay signed in.
import 'package:flutter/material.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import 'env.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Supabase.initialize(
url: Env.supabaseUrl,
publishableKey: Env.supabaseAnonKey,
);
runApp(const MyApp());
}Step 3: turn on Apple in Supabase
This is the step that decides whether everything else works, so it is worth doing carefully.
- Open your project in the Supabase dashboard, then Authentication, then Sign In / Providers, then Apple.
- Switch the provider on.
- Find the field called Client IDs. This is the list of apps whose Apple tokens Supabase will accept. Add the bundle ID of the app that asks for sign-in. If you add more than one, separate them with commas.
- Save.
For the native flow, the Client IDs list is the setting that matters. The Services ID and the secret key that Supabase also asks about belong to the web flow, so you can leave them out if you only use the native button.
Which bundle ID goes in the list depends on whether you are testing or shipping, and that is the subtle part. Step 6 explains it, and it is the reason most people get an error on the first try.
Step 4: the button and the code behind it
Here is the method from our sign-in screen. It generates a random nonce, asks Apple to sign the user in, and gives the identity token to Supabase.
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:pointycastle/digests/sha256.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class AuthScreen extends StatefulWidget {
const AuthScreen({super.key});
@override
State<AuthScreen> createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
bool _busy = false;
String? _msg;
Future<void> _apple() async {
setState(() {
_busy = true;
_msg = null;
});
try {
// 1. A random value only this sign-in attempt knows.
final rnd = Random.secure();
final raw = base64UrlEncode(
List<int>.generate(32, (_) => rnd.nextInt(256)),
);
// 2. Apple gets the SHA-256 hash of it, written in hex.
final hashed = SHA256Digest().process(
Uint8List.fromList(utf8.encode(raw)),
);
final hex = hashed
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join();
// 3. Show Apple's sign-in sheet.
final cred = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
nonce: hex,
);
final token = cred.identityToken;
if (token == null) throw 'Apple returned no identity token';
// 4. Supabase gets the token and the original, unhashed value.
final auth = Supabase.instance.client.auth;
await auth.signInWithIdToken(
provider: OAuthProvider.apple,
idToken: token,
nonce: raw,
);
// 5. Apple sends the name only the first time. Save it now.
final name = [cred.givenName, cred.familyName]
.whereType<String>()
.join(' ')
.trim();
if (name.isNotEmpty) {
await auth.updateUser(
UserAttributes(data: {'name': cred.givenName ?? name}),
);
}
} on SignInWithAppleAuthorizationException catch (e) {
// Closing the sheet is not an error, so say nothing.
if (e.code != AuthorizationErrorCode.canceled) {
_msg = 'Apple sign-in failed: ${e.message}';
}
} on AuthException catch (e) {
_msg = e.message;
} catch (e) {
_msg = 'Apple sign-in failed: $e';
}
if (mounted) setState(() => _busy = false);
}
@override
Widget build(BuildContext context) => Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (_msg != null)
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Text(_msg!,
style: const TextStyle(color: Colors.redAccent)),
),
OutlinedButton.icon(
onPressed: _busy ? null : _apple,
icon: const Icon(Icons.apple),
label: const Text('Continue with Apple'),
style: OutlinedButton.styleFrom(
minimumSize: const Size.fromHeight(52),
shape: const StadiumBorder(),
),
),
],
),
),
),
);
}A few details are worth knowing, because each one answers a question people ask.
- The nonce. It stops someone from taking a token meant for one sign-in and replaying it for another. Apple receives only the hash. Supabase receives the original value and hashes it again to check that the two match. If you send the same value to both, sign-in fails with a nonce mismatch.
- Closing the sheet. If the person taps Cancel, Apple throws an exception with the code
canceled. That is a choice, not a failure, so the code ignores it. - The name. Apple gives your app the person's name only the first time they approve it. On every later sign-in it comes back empty. Save it straight away, as the example does, or you will not get another chance. If you have signed in with this Apple ID before, the app should fall back to something else, such as the first part of the email.
- The email. The person can choose to hide it. Apple then sends a private relay address. Treat it as a normal address, but do not assume it looks like a real name.
Step 5: show the right screen
Supabase tells the app whenever the session changes, so the simplest way to switch between the sign-in screen and the rest of the app is to listen to that stream.
class AuthGate extends StatelessWidget {
const AuthGate({super.key});
@override
Widget build(BuildContext context) {
final auth = Supabase.instance.client.auth;
return StreamBuilder<AuthState>(
stream: auth.onAuthStateChange,
builder: (context, _) => auth.currentSession == null
? const AuthScreen()
: const HomeScreen(),
);
}
}Use AuthGate as the app's home screen. When sign-in succeeds, the session appears, the stream fires, and the home screen replaces the sign-in screen without any code that navigates by hand.
Step 6: try it on your phone
Start the app with Zapbird as usual.
zapbird startScan the QR code with the runner, tap Continue with Apple, and approve with Face ID. If everything is set, you land on your home screen. If you see an error from Supabase saying the audience of the token is not acceptable, you have found the setting from step 3, and the fix takes under a minute.
Here is what happens. Apple builds the identity token for the app that actually asked for sign-in. While you test inside Zapbird, your code runs inside the runner app, so the app that asks is the runner, and the token carries the runner's bundle ID, not your own. Supabase checks that ID against the Client IDs list, does not find it, and refuses.
The fix is to add the runner's bundle ID to the list, after your own, with a comma. The runner's current ID is dev.zapbird.runner. The exact value Apple used is in the error message, and an older runner build may use a different one, so copy it from there if it differs. Save, tap the button again, and it works. You do not need to reload the app.
com.yourcompany.yourapp,dev.zapbird.runnerThis is not a quirk of Zapbird. Any app that runs other apps has the same property: the identity belongs to the app that is signed, and the previewed code borrows it. Expo Go works the same way, and its documentation tells you to allow its bundle ID while you test. The app's own bundle ID is not on the phone as a separate app, so Apple has no way to issue a token for it.
Step 7: permissions and the config file
Zapbird keeps the things a store build needs in one file, zapbird.yaml. It adds an entry when your code starts using a package that needs one. For this feature it records that your app uses Sign in with Apple.
permissions:
sign_in_with_apple:
used_by: [sign_in_with_apple]Nothing here changes the preview, because the runner already has the capability. It matters when you build for the store. Run zapbird config check to see what is still missing, and zapbird config apply to write the settings into the iOS project. The zapbird.yaml reference lists every field.
Does it only work with Supabase?
No. We used Supabase because it was the backend of the app we tested, but nothing about Sign in with Apple belongs to it. Everything up to the moment Apple hands you the identity token is the same whichever backend you use: the sign_in_with_apple package, the nonce, the Apple sheet, the name that arrives only once, and the Apple developer setup. Only the last call changes, the one that gives the token to your backend.
Here is how that last call looks elsewhere. We built and tested this post with Supabase only, so treat the other versions as a guide and check each provider's current documentation.
- Firebase Authentication. Hand the token to Firebase as an Apple credential, with the original, unhashed nonce:
OAuthProvider('apple.com').credential(idToken: token, rawNonce: raw), then pass it toFirebaseAuth.instance.signInWithCredential(...). The list of allowed Apple client IDs lives in the Firebase console. - Your own server. Send the identity token and the original nonce to your API. Your server must check the token's signature against Apple's public keys, that the issuer is
https://appleid.apple.com, that the audience is one of your bundle IDs, that the token has not expired, and that the token's nonce equals the SHA-256 hash of the nonce you sent. If all of that passes, it creates its own session for the person. - Other services such as Auth0, Appwrite, Clerk or AWS Cognito offer a similar way to sign in with an Apple token, though some only support the web flow. Look for a native or ID-token option.
The runner behaves the same way with every backend. While you test inside Zapbird, Apple issues the token for the runner's bundle ID, so the list of allowed apps on your backend needs that ID next to your own. In Supabase that list is the Client IDs field. In Firebase it is the allowed Apple client IDs. On your own server it is the audience you accept.
Before you ship
When you build the app yourself, it is signed with its own bundle ID, and Apple issues tokens for that ID. The code does not change at all. The settings around it do.
- Choose your own bundle ID. Replace the Flutter default, which looks like
com.example.yourapp, with one you own. Check the current value inios/Runner.xcodeproj/project.pbxprojby searching forPRODUCT_BUNDLE_IDENTIFIER. - Register it with Apple. In the Apple developer portal, create the App ID and enable the Sign in with Apple capability for it.
- Add the capability in Xcode. Open
ios/Runner.xcworkspace, choose your target, and add Sign in with Apple under Signing and Capabilities. - Add the ID to Supabase. Put your real bundle ID in the Client IDs list. Keep the runner's ID there too if you still test with Zapbird. Both can be listed at once.
- Run `zapbird config check` and write an honest reason for every permission your app asks for. Apple rejects vague ones.
- Test a real build. Build with
flutter build iosand install it through TestFlight before you rely on it. Our own test ran inside the runner, so it did not exercise your final bundle ID or capability, and that is the one thing a preview cannot prove.
Apple also expects apps that let people create an account to let them delete it from inside the app. If you use Sign in with Apple, that includes revoking the Apple token when an account is deleted. The rules change from time to time, so read Apple's current requirements before you submit. Our store builds guide covers the rest of the path.
When it does not work
- An error about the token's audience. The bundle ID is not in the Client IDs list. Copy the ID from the error, add it after your own, and save.
- A nonce error. The hashed value went to Supabase, or the raw value went to Apple. Apple gets the hash. Supabase gets the original.
- No identity token. The sign-in did not finish. On a device, check that an Apple ID is signed in under Settings. On a simulator, sign in to iCloud first.
- The sheet closes and nothing happens. The person cancelled. The code ignores that on purpose.
- The name is empty. Apple only sends it the first time. Remove the app from your Apple ID's list under Settings, then Apple ID, then Sign-In and Security, and sign in again to see the consent screen once more.
- It works in the runner but not in your build. Your own bundle ID is missing from the Client IDs list, or the capability is not enabled for it.
The troubleshooting page lists the Zapbird side of the same problems, such as pairing and packages that need a store build.
A note on keeping it safe
- The anon key can be in the app, because it is public by design. The thing that protects your data is Row Level Security on your tables. Turn it on, and test with two accounts that one cannot read the other's rows.
- Never put a service role key, a database password or an API key for a paid service in the app. Anything in the app can be read by anyone who installs it. Keep those in server code, such as a Supabase Edge Function, and read them from secrets there.
- Zapbird already hides keys and tokens in the output it prints, and refuses to send a project that contains server-side keys. See the security page for how.
Where to go next
With sign-in working, the next steps are the ones every app needs: a table for each person's data with Row Level Security, a screen for the profile, and a way to sign out and delete the account. The same pattern, a native sheet that returns a token you pass to signInWithIdToken, also works for other providers that offer a native flow.
If you build this and something does not match what we described, tell us. This post comes from one app and one phone, and we would like to hear what other setups look like.