애플 로그인

김동연·2025년 6월 9일

개발기록일지(Flutter)

목록 보기
18/32

애플로그인 임시

Apple 로그인 기능 구현


1. Apple Developer 계정 소유자 or 관리자가 해야 할 작업

이 작업들은 Apple Developer Program에 유료 등록된 계정 소유자만 수행할 수 있습니다.

1.1 Apple Developer Program 유료 등록

  • 연 129,000원 비용 발생
  • 개인 혹은 조직 계정 형태로 등록 가능
  • 등록 후 Apple Developer 사이트에서 인증 가능

1.2 App ID (Bundle ID) 생성

  • Apple Developer 사이트 접속: https://developer.apple.com/account

  • 좌측 메뉴에서 "Identifiers" 선택

  • "+" 버튼을 눌러 새로운 App ID 생성

  • App Name은 자유롭게 입력

  • Bundle ID는 Flutter 프로젝트의 ios/Runner.xcodeproj/project.pbxprojPRODUCT_BUNDLE_IDENTIFIER와 일치해야 함

    • 예시: com.companyname.appname

1.3 Capabilities에서 Sign in with Apple 활성화

  • App ID 생성 과정 중 "Capabilities" 항목에서 "Sign in with Apple" 선택
  • 이미 생성된 App ID의 경우, 수정하여 활성화 가능

1.4 Provisioning Profile 생성 또는 수정

  • "Profiles" 메뉴에서 새로운 Provisioning Profile 생성
  • 위에서 생성한 App ID 선택
  • 사용할 개발자 인증서 선택
  • 필요한 경우 개발 기기 UDID 추가
  • Sign in with Apple이 포함된 상태로 프로파일 생성 완료

1.5 Xcode에서 Capabilities 설정

  • macOS에서 Xcode 실행 후 Flutter 프로젝트의 ios/Runner.xcworkspace 열기
  • 좌측 TARGETS > Runner 클릭
  • "Signing & Capabilities" 탭 선택
  • "+" 버튼을 눌러 "Sign in with Apple" 추가
  • "Team" 항목이 Apple Developer에 등록된 계정으로 설정되어 있는지 확인

1.6 변경 사항 저장 및 전달

  • Capability가 추가된 상태로 .xcworkspace, .xcodeproj, .pbxproj, project.pbxproj 등이 포함된 iOS 프로젝트를 개발자에게 전달
  • Git으로 Push하거나 전체 프로젝트 압축 전달 가능

2. Flutter 개발자가 해야 할 작업

소유자가 위 작업을 마친 후에는 개발자가 Apple 로그인 기능을 Flutter 앱 내에서 구현하고 테스트할 수 있습니다.

2.1 패키지 추가

pubspec.yaml에 다음 패키지들을 추가

dependencies:
  sign_in_with_apple: ^5.0.0
  firebase_auth: ^4.0.0
  cloud_firestore: ^4.0.0
flutter pub get

2.2 Apple 로그인 로직 구현 (sign_in_with_apple 패키지 사용)

import 'package:sign_in_with_apple/sign_in_with_apple.dart';

Future<AppleIDCredential?> signInWithApple() async {
  try {
    final credential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName,
      ],
    );
    return credential;
  } catch (e) {
    print("Apple 로그인 실패: $e");
    return null;
  }
}

2.3 Firebase Auth 연동

import 'package:firebase_auth/firebase_auth.dart';

Future<User?> firebaseSignInWithApple(AppleIDCredential credential) async {
  final oAuthProvider = OAuthProvider("apple.com");

  final authCredential = oAuthProvider.credential(
    idToken: credential.identityToken,
    accessToken: credential.authorizationCode,
  );

  final userCredential =
      await FirebaseAuth.instance.signInWithCredential(authCredential);

  return userCredential.user;
}

2.4 Firestore에 사용자 정보 저장

import 'package:cloud_firestore/cloud_firestore.dart';

Future<void> saveUserToFirestore(User user, AppleIDCredential appleInfo) async {
  final docRef = FirebaseFirestore.instance.collection('users').doc(user.uid);

  await docRef.set({
    'userId': user.uid,
    'email': user.email ?? '',
    'name': '${appleInfo.givenName ?? ''} ${appleInfo.familyName ?? ''}'.trim(),
    'provider': 'apple',
    'photoUrl': user.photoURL ?? '',
    'createdAt': FieldValue.serverTimestamp(),
  }, SetOptions(merge: true));
}

2.5 전체 통합 로직

Future<void> handleAppleSignIn() async {
  final appleCredential = await signInWithApple();
  if (appleCredential == null) return;

  final firebaseUser = await firebaseSignInWithApple(appleCredential);
  if (firebaseUser == null) return;

  await saveUserToFirestore(firebaseUser, appleCredential);
}

2.6 UI 버튼 연결

SignInWithAppleButton(
  onPressed: () async {
    await handleAppleSignIn();
  },
  style: SignInWithAppleButtonStyle.black,
)

2.7 iOS 설정 파일 수정

ios/Runner/Info.plist 파일 내 다음 항목이 포함되어 있어야 함

<key>CFBundleURLTypes</key>
<array>
  <dict>
    <key>CFBundleURLSchemes</key>
    <array>
      <string>com.companyname.appname</string>
    </array>
  </dict>
</array>

2.8 Firestore 보안 규칙 예시

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth != null && request.auth.uid == userId;
    }
  }
}

3. 테스트플라이트 업로드 및 테스트

3.1 Xcode에서 Archive

  • Product > Archive 클릭
  • Archive 완료 후 Distribute App → App Store Connect 선택
  • 업로드 완료 후 App Store Connect의 TestFlight에서 빌드 확인

3.2 테스터 등록 및 다운로드

  • App Store Connect > TestFlight > 테스터 이메일 등록
  • 테스터는 iOS 디바이스에서 TestFlight 앱 설치 후 초대 링크 클릭
  • 로그인 상태에서 Apple 로그인 기능 정상 동작 확인

0개의 댓글