본문 바로가기
Flutter/Firebase

플러터에서 Apple 로그인 구현하기: Firebase 연동 가이드

by Maccrey Coding 2024. 8. 29.
반응형

 

 

애플 앱 스토어에 앱을 배포할 때, Apple 로그인을 지원하는 것은 필수적인 요구사항 중 하나입니다.

Flutter에서 Apple 로그인을 구현하는 방법을 단계별로 설명하겠습니다.

이 가이드에서는 sign_in_with_apple 패키지를 사용하여 iOS와 macOS에서 Apple 로그인을 구현하는 방법을 다룹니다.

 

1. 프로젝트 설정

1.1 Apple Developer 설정

Apple 로그인을 사용하려면 Apple Developer 계정에서 설정을 완료해야 합니다.

  1. Apple Developer 계정에 로그인한 후, Identifiers에서 앱 ID를 생성합니다.
  2. Sign In with Apple을 활성화합니다.
  3. Service ID를 생성하여 Redirect URL을 설정합니다. 이 URL은 Apple에서 인증이 완료된 후 사용자를 리다이렉트할 주소입니다.
  4. 생성된 Service IDClient ID를 기록해 둡니다.

1.2 Flutter 프로젝트에 패키지 추가

pubspec.yaml 파일에 sign_in_with_apple 패키지를 추가합니다.

dependencies:
  sign_in_with_apple: latest_version
  firebase_auth: latest_version
  firebase_core: latest_version

 

sign_in_with_apple 패키지는 Apple 로그인 UI와 기능을 제공하며, firebase_auth 패키지를 통해 Firebase와 통합할 수 있습니다.

 

sign_in_with_apple | Flutter package

Flutter bridge to initiate Sign in with Apple (on iOS, macOS, and Android). Includes support for keychain entries as well as signing in with an Apple ID.

pub.dev

2. Apple 로그인 구현

2.1 iOS 설정

  1. ios/Runner.xcworkspace를 열고 Xcode에서 프로젝트 설정을 업데이트합니다.
  2. Signing & Capabilities 탭에서 Apple Developer 계정을 통해 Sign In with Apple 기능을 추가합니다.
  3. Runner > Info.plist 파일에 아래와 같은 설정을 추가합니다.
<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleTypeRole</key>
        <string>Editor</string>
        <key>CFBundleURLName</key>
        <string>SignInWithApple</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>your.bundle.identifier</string>
        </array>
    </dict>
</array>
<key>NSAppleMusicUsageDescription</key>
<string>Your app uses Apple Sign-In to authenticate users.</string>
<key>NSFaceIDUsageDescription</key>
<string>Your app uses Face ID for a quick and secure sign-in experience.</string>

2.2 Apple 로그인 버튼 구현

이제 Flutter 앱에서 Apple 로그인 버튼을 구현합니다. lib/services/auth_service.dart 파일을 생성하여 Apple 로그인 로직을 처리합니다.

import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:firebase_auth/firebase_auth.dart';

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  Future<User?> signInWithApple() async {
    try {
      final appleCredential = await SignInWithApple.getAppleIDCredential(
        scopes: [
          AppleIDAuthorizationScopes.email,
          AppleIDAuthorizationScopes.fullName,
        ],
      );

      final oauthCredential = OAuthProvider("apple.com").credential(
        idToken: appleCredential.identityToken,
        accessToken: appleCredential.authorizationCode,
      );

      final UserCredential userCredential = await _auth.signInWithCredential(oauthCredential);
      return userCredential.user;
    } catch (e) {
      print("Error in Apple Sign-In: $e");
      return null;
    }
  }

  Future<void> signOut() async {
    await _auth.signOut();
  }
}

2.3 Apple 로그인 버튼 UI 구현

이제 Apple 로그인 버튼을 Flutter UI에 추가합니다. lib/screens/login_screen.dart 파일에 Apple 로그인 버튼을 추가합니다.

import 'package:flutter/material.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:your_project_name/services/auth_service.dart';

class LoginScreen extends StatelessWidget {
  final AuthService _authService = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Sign in with Apple'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            SignInWithAppleButton(
              onPressed: () async {
                User? user = await _authService.signInWithApple();
                if (user != null) {
                  // 로그인 성공 시, 메인 화면으로 이동
                  Navigator.pushReplacementNamed(context, '/home');
                } else {
                  // 로그인 실패 시, 에러 메시지 표시
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(content: Text('Apple Sign-In Failed')),
                  );
                }
              },
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                await _authService.signOut();
                Navigator.pushReplacementNamed(context, '/login');
              },
              child: Text('Sign Out'),
            ),
          ],
        ),
      ),
    );
  }
}

3. 테스트 및 배포

모든 설정이 완료되면 앱을 실행하여 Apple 로그인이 제대로 동작하는지 확인합니다. 앱이 정상적으로 작동하면, iOS 앱 스토어에 배포할 수 있습니다.

 

이제 Flutter 앱에서 Apple 로그인을 성공적으로 구현할 수 있습니다.

이 가이드가 여러분의 Flutter 프로젝트에서 Apple 로그인을 추가하는 데 도움이 되기를 바랍니다.

Apple 로그인을 통해 사용자 인증을 간편하게 처리하여 더욱 완벽한 사용자 경험을 제공할 수 있습니다.

공감과 댓글은 저에게 큰 힘이 됩니다.

Starting Google Play App Distribution! "Tester Share" for Recruiting 20 Testers for a Closed Test.

 

Tester Share [테스터쉐어] - Google Play 앱

Tester Share로 Google Play 앱 등록을 단순화하세요.

play.google.com

 

반응형