Apple Sign in / sign up with Flutter
2 min readAug 19, 2023
Implementing Apple Sign-In in a Flutter app involves a few steps. Apple Sign-In is a secure way for users to sign in to your app using their Apple ID. Here’s a step-by-step guide to integrating Apple Sign-In into your Flutter app:
- Set Up Your Apple Developer Account:
- If you haven’t already, create an Apple Developer account at Apple Developer.
- Create an App ID for your Flutter app in the Apple Developer portal.
2 Enable Sign-In with Apple:
- In the Apple Developer portal, navigate to your App ID, and under “Capabilities,” enable “Sign In with Apple.”
3 Configure App in Firebase (Optional):
- If you’re using Firebase in your Flutter app, you can configure Apple Sign-In in the Firebase Console. This step is optional but can simplify the authentication process.
- and enable apple signin provider
4 Add Dependencies:
- Open your Flutter project’s
pubspec.yaml
file and add the following dependencies:
sign_in_with_apple: ^5.0.0
crypto: ^3.0.3
import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
/// Generates a cryptographically secure random nonce, to be included in a
/// credential request.
String generateNonce([int length = 32]) {
final charset =
'0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._';
final random = Random.secure();
return List.generate(length, (_) => charset[random.nextInt(charset.length)])
.join();
}
/// Returns the sha256 hash of [input] in hex notation.
String sha256ofString(String input) {
final bytes = utf8.encode(input);
final digest = sha256.convert(bytes);
return digest.toString();
}
Future<UserCredential> signInWithApple() async {
// To prevent replay attacks with the credential returned from Apple, we
// include a nonce in the credential request. When signing in with
// Firebase, the nonce in the id token returned by Apple, is expected to
// match the sha256 hash of `rawNonce`.
final rawNonce = generateNonce();
final nonce = sha256ofString(rawNonce);
// Request credential for the currently signed in Apple account.
final appleCredential = await SignInWithApple.getAppleIDCredential(
scopes: [
AppleIDAuthorizationScopes.email,
AppleIDAuthorizationScopes.fullName,
],
nonce: nonce,
);
// Create an `OAuthCredential` from the credential returned by Apple.
final oauthCredential = OAuthProvider("apple.com").credential(
idToken: appleCredential.identityToken,
rawNonce: rawNonce,
);
// Sign in the user with Firebase. If the nonce we generated earlier does
// not match the nonce in `appleCredential.identityToken`, sign in will fail.
return await FirebaseAuth.instance.signInWithCredential(oauthCredential);
}
than call this func to the apple signin Button
ElevatedButton(
onPressed: signInWithApple,
child: Text("Sign in with Apple"),
),