Firebase Google Login

오픈소스·2025년 2월 15일
post-thumbnail

Firebase Authentication 에서 Google을 추가하고 나면, 다음과 같은 화면이 나타납니다.

구성 파일 업데이트

  • google-services.json --> android/app/google-services.json
  • GoogleService-Info.plist --> ios/Runner/GoogleService-Info.plist

iOS 설정

  • iOS/Runner/Info.plist에 다음 추가

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>YOUR-REVERSED-CLIENT-ID</string>
            </array>
        </dict>
    </array>

auth_service.dart

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

class AuthService {
  final FirebaseAuth _auth = FirebaseAuth.instance;
  final GoogleSignIn _googleSignIn = GoogleSignIn();

  // Google 로그인
  Future<UserCredential?> signInWithGoogle() async {
    try {
      // Google 로그인 진행
      final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
      if (googleUser == null) return null;

      // 인증 정보 가져오기
      final GoogleSignInAuthentication googleAuth = await googleUser.authentication;

      // credential 생성
      final credential = GoogleAuthProvider.credential(
        accessToken: googleAuth.accessToken,
        idToken: googleAuth.idToken,
      );

      // Firebase에 로그인
      return await _auth.signInWithCredential(credential);
    } catch (e) {
      print('Google 로그인 실패: $e');
      return null;
    }
  }

  // 로그아웃
  Future<void> signOut() async {
    await _googleSignIn.signOut();
    await _auth.signOut();
  }
}

login_screen.dart

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

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

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('로그인')),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            final user = await _authService.signInWithGoogle();
            if (user != null) {
              // 로그인 성공 처리
              Navigator.pushReplacementNamed(context, '/home');
            } else {
              // 로그인 실패 처리
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(content: Text('로그인에 실패했습니다.')),
              );
            }
          },
          child: Text('Google로 로그인'),
        ),
      ),
    );
  }
}

0개의 댓글