Firebase 인증 (Authentcation) 소개
개요
Firebase Authentication은 사용자 관리를 편리하게 할 수 있게 도와주며, 보안에 관한 걱정 없이 서비스에 집중할 수 있게 합니다.
Firebase는 내부적으로 안전한 인증 시스템을 구축하고 있어, 개발자는 복잡한 인증 시스템을 직접 구현할 필요 없이 Firebase의 인증 기능을 이용할 수 있습니다.

장점
- 다양한 인증 방법 지원:
- Firebase는 이메일 및 비밀번호, Google, Facebook, Twitter, Github 등 다양한 소셜 로그인 방식 뿐만 아니라, 전화번호 인증과 같은 방식도 지원합니다.
- 보안 및 관리:
- Firebase Authentication은 사용자의 로그인 정보를 안전하게 관리하며, Google의 보안 인프라 위에서 운영됩니다. 또한 Firebase 콘솔을 통해 사용자 관리가 가능합니다.
- 사용자 경험 향상:
- 간단한 API와 Flutter의 뛰어난 UI 구성 능력을 결합하여, 사용자에게 매끄러운 로그인 경험을 제공할 수 있습니다.
- 쉬운 통합:
- Firebase Authentication은 Flutter와의 통합이 매우 간단합니다.
- Firebase Flutter 라이브러리를 프로젝트에 추가하기만 하면, 몇 줄의 코드로 인증 기능을 구현할 수 있습니다.
인증 종류
이메일/비밀번호 인증
가장 기본적인 인증 방식으로, 사용자가 이메일 주소와 비밀번호를 사용하여 계정을 생성하고 로그인할 수 있습니다.
Google 인증
Google 계정을 사용하여 로그인하는 방법입니다.
사용자는 자신의 Google 계정을 사용하여 앱에 로그인할 수 있습니다.
Facebook 인증
Facebook 계정으로 사용자 인증을 할 수 있는 방법입니다.
사용자는 자신의 Facebook 계정을 사용하여 앱에 로그인할 수 있습니다.
전화번호 인증
자의 전화번호를 이용한 인증 방식으로, SMS를 통해 전송된 일회용 코드를 사용하여 인증합니다.
이 방법은 전화번호를 사용자 식별 정보로 사용하는 앱에 적합합니다.
익명 인증
사용자가 앱에 로그인할 수 있도록 하면서도, 사용자로부터 어떠한 개인 식별 정보도 수집하지 않는 방식입니다.
사용자는 익명으로 앱을 사용할 수 있으며, 나중에 필요시 다른 인증 방법으로 전환할 수 있습니다.
Rules
인증이 된 사용자만 사용할 수 있도록 Firebase Console에서 Rule을 다음과 같이 설정할 수 있다.
{ "rules": { ".read": "auth != null", ".write": "auth != null" } }
Class 및 Methods
패키지 추가
다음 명령어로 firebase 인증 패키지를 추가합니다.
$ flutter pub add firebase_core firebase_auth google_sign_in flutter_facebook_auth
다음 패키지를 인증을 구현할 코드에 추가합니다.
import 'package:firebase_auth/firebase_auth.dart';
FirebaseAuth Class
Firebase Authentication의 핵심 클래스로, 인증 관련 작업을 수행합니다.
- instance:
- FirebaseAuth의 싱글톤 인스턴스에 접근합니다.
- 대부분의 인증 작업은 이 인스턴스를 통해 이루어집니다.
FirebaseAuth auth = FirebaseAuth.instance;
- currentUser:
- 현재 로그인한 사용자의 정보를 담고 있는
User
객체를 반환합니다. - 사용자가 로그인하지 않았다면
null
을 반환합니다.
- 현재 로그인한 사용자의 정보를 담고 있는
User? user = FirebaseAuth.instance.currentUser;
- signInWithEmailAndPassword(String email, String password):
- 이메일과 비밀번호를 사용하여 사용자 로그인을 수행합니다.
- 성공 시
UserCredential
객체를 반환합니다.
UserCredential userCredential = await FirebaseAuth.instance.signInWithEmailAndPassword(email: 'user@example.com', password: 'superSecretPassword');
- createUserWithEmailAndPassword(String email, String password):
- 이메일과 비밀번호를 사용해 새로운 사용자 계정을 생성합니다.
- 성공 시
UserCredential
객체를 반환합니다.
UserCredential userCredential = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: 'user@example.com', password: 'superSecretPassword');
- signOut():
- 현재 로그인한 사용자를 로그아웃합니다.
await FirebaseAuth.instance.signOut();
User Class
Firebase Authentication에서 사용자의 정보를 나타내는 클래스입니다.
- uid:
- 사용자의 고유 ID입니다.
- email:
- 사용자의 이메일 주소입니다.
- displayName:
- 사용자의 표시 이름입니다.
- photoURL:
- 사용자의 프로필 사진 URL입니다.
- emailVerified:
- 사용자의 이메일 인증 상태를 나타냅니다.
UserCredential Class
인증 작업의 결과로 반환되는 클래스로, User
객체와 관련 메타데이터를 포함합니다.
- user:
- 인증 작업을 통해 반환된
User
객체입니다.
- 인증 작업을 통해 반환된
- credential:
- 인증 작업에 사용된 자격 증명입니다. 예를 들어, 이메일과 비밀번호, 소셜 로그인 토큰 등이 될 수 있습니다.
Providers
Firebase Authentication은 이메일/비밀번호 인증 외에도 여러 인증 방법을 지원합니다.
각 인증 방법은 해당 서비스의 Provider
를 통해 AuthCredential
객체를 생성하고, 이를 signInWithCredential
메서드에 전달하여 사용자를 인증합니다.
- GoogleAuthProvider
- FacebookAuthProvider
- TwitterAuthProvider
- GithubAuthProvider
- PhoneAuthProvider
예제
1. Console에서 인증(Authentication) 서비스 활성화
firebase console에서 인증(Authentication) 섹션으로 이동합니다.
[Build] -> [Authentication] -> (Get Started) 를 클릭후 인증 방법을 설정합니다.
(본 예제 에서는 Email/Password, Google인증방식을 사용해 봅니다.)


Google은 계정정보, Facebook은 메타 개발자 페이지에서 APP ID와 App Secret을 발급받아야한다.)
2. Firebase 인증 초기화 및 패키지 설치
인증에 사용할 패키지들을 추가합니다.
$ flutter pub add firebase_auth google_sign_in
3. Google 인증 구현
참조: [Flutter] Firebase Authentication 사용해 보기 1편
Fingerprint 추가
Android에서 앱을 확인하는 인증서 3개를 등록하여야 한다. (Debug, Release, Store)
- Debug: gradlew signingReport를 이용하여 SHA-1키 생성합니다.
- Release: keystore 생성할 때 획득할 수 있습니다.
- Store: Play Console에 앱 배포할 때 Google에서 키를 발급해 주는데 발급받은 인증서를 넣어야 합니다.
본 예제에서는 Debug의 인증서를 만들어서 추가해보도록 하겠습니다.
flutter 프로젝트의 android 폴더로 이동 후, gradlew signingReport를 이용하여 SHA-1키를 생성합니다.
(flutter project의 root 폴더 경로에서 ..)
$ cd android $ gradlew signinReport
이때, Report 되는 SHA1에 해당하는 키를 복사합니다.
Project Setting -> Android App 선택 -> Add fingerprint 버튼 클릭

팝업되는 Certificate fingerprint에 위에서 복사한 키를 붙여 넣은후 Save 합니다.

이후 Android App은 google-services.json 파일을 다운 받고,

flutter 프로젝트의 /android/app 폴더의 google-services.json 파일을 다운받은 파일로 교체 합니다.

IOS App은 GoogleService-Info.plist를 다운 받습니다.

flutter 프로젝트의 /ios/Runner/GoogleService-Info.plist를 교체합니다.

로그인 Page 구현 in Flutter Code
firebase_auth
와 google_sign_in
패키지를 코드에 import 합니다.
import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart';
FirebaseAuth의 singleton sintance에 접근합니다. 이 인스턴스를 통해 인증작업이 이루어집니다.
class _AuthPageState extends State<AuthPage> { final FirebaseAuth _auth = FirebaseAuth.instance; }
로그인 성공 시, MemoPage
로 이동하는 라우팅하는 함수를 구현합니다.
void _gotoMemoPage() { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => const MemoPage(), ), ); }
google_sign_in
패키지의 GoogleSignInAccount
Class, GoogleSignInAuthentication
Class, GoogleAuthProvider
를 이용하여
Google 인증을 수행할 함수를 구현합니다.
void _signInWithGoogle() async { try { final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn(); final GoogleSignInAuthentication? googleAuth = await googleUser?.authentication; final credential = GoogleAuthProvider.credential( accessToken: googleAuth?.accessToken, idToken: googleAuth?.idToken, ); final userCredential = await _auth.signInWithCredential(credential); print("Logged in with Google: ${userCredential.user}"); _gotoMemoPage(); } catch (e) { print(e); } }
버튼을 누르면 로그인할 수 있도록 구현합니다.
ElevatedButton( onPressed: _signInWithGoogle, child: const Row( children: [ Icon(FontAwesomeIcons.google, color: Colors.red), SizedBox(width: 10), Text("Sign in with Google"), ], ), ),
결과

4. Email을 이용한 로그인 구현
Email 정보 추가
Firebase Console -> Authentication -> Users 에서 로그인할 Email 정보를 추가합니다.

구현
TextFormField
와 TextEditingController
를 통해 Email 주소와 비밀번호를 입력받습니다.
final TextEditingController _idController = TextEditingController(); final TextEditingController _passwordController = TextEditingController();
TextFormField( controller: _idController, decoration: const InputDecoration(labelText: "Email"), ), const SizedBox(height: 8), TextFormField( controller: _passwordController, obscureText: true, // 비밀번호 숨김 처리 decoration: const InputDecoration(labelText: "Password"), ),
입력받은 Email과 Password를 이용하여 로그인 하는 함수를 구현했고,
로그인이 성공하면 마찬가지로 MemoPage
로 이동하도록 하였습니다.
signInWithEmailAndPassword()
method를 사용하여 Email과 Password를 이용하여 인증하도록 구현합니다.
void _signInWithEmail() async { try { final userCredential = await _auth.signInWithEmailAndPassword( email: _idController.text, password: _passwordController.text); print("Logged in with email: ${userCredential.user}"); _gotoMemoPage(); } catch (e) { print(e); } }
결과
