ChatGPT와 아래 Mitch Koko의 튜토리얼 영상을 참고했음을 먼저 밝힙니다.
https://www.youtube.com/playlist?list=PLlvRDpXh1Se4Ceivpg8KrGvzb8BL9BHwo
OAuth2를 구현하기 전에, 먼저 OAuth2가 뭔지부터 알아보겠습니다.
즉, 구글, 애플, 페이스북 등의 아이디를 이용한 로그인을 할 수 있게 하는게 OAuth 프로토콜입니다. 저는 이걸 제 Flutter 클라이언트에 연결하고자 합니다.
1. 클라이언트 준비
클라이언트는 아래와 같이 UI 위주로 구현되어 있습니다.
2. Flutter 코딩 및 Firebase 설정
먼저 ChatGPT에 OAuth2 로그인과 회원관리를 위해 뭘 해야하는지 물어봤습니다.
1, 2번은 지난 4주차때 해서 익숙하군요! 3번은 아래와 같이 하면 될 것 같습니다.
2-1. 라이브러리 설치
firebase_core, firebase_auth, google_sign_in 라이브러리를 설치하려면 보통 아래와 같이 하면 됩니다.
flutter pub add [추가하고자 하는 라이브러리]각 라이브러리에 대한 설명은 pub.dev 사이트에서 찾을 수 있는데, 예를 들어 https://pub.dev/packages/[라이브러리 이름] 과 같이 작성하면 해당 라이브러리에 대한 설명을 찾아볼 수 있습니다.
2-2. flutter 코드
main.dart 부분에 Firebase를 초기화 하는 코드를 넣습니다.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MyApp());
}로그인 여부를 확인할 수 있는
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthService {
signInWithGoogle() async {
// begin interactive sign-in process
final GoogleSignInAccount? gAccount = await GoogleSignIn().signIn();
// obtain auth details from the request
final GoogleSignInAuthentication gUser = await gAccount!.authentication;
// create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: gUser.accessToken,
idToken: gUser.idToken,
);
// lets sign in
return await FirebaseAuth.instance.signInWithCredential(credential);
}
}버튼을 클릭하면 저 서비스를 실행하도록 해줍니다!
class SquareTile extends StatelessWidget {
...
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => AuthService().signInWithGoogle(),
);
}
}2-3. Settings
Flutter는 멀티 플랫폼을 지원하는 프레임워크입니다. 따라서 OAuth2를 적용하기 위해서는 Android, iOS, web 등의 연동을 위한 설정을 따로 해줘야 합니다. Android를 기준으로 firebase와 연동하는 방법을 알아보겠습니다. 이 세팅이 코드 구현만큼이나 일이 많습니다. ^^;
아래와 같이 로그인 → flutterfire_cli 활성화 → PATH 입력 → flutterfire configure를 통해 설정해줍니다.
```
% firebase login
% dart pub global activate flutterfire_cli
Package flutterfire_cli is currently active at version 0.2.7.
The package flutterfire_cli is already activated at newest available version.
To recompile executables, first run `dart pub global deactivate flutterfire_cli`.
Installed executable flutterfire.
Warning: Pub installs executables into $HOME/.pub-cache/bin, which is not on your path.
You can fix that by adding this to your shell's config file (.bashrc, .bash_profile, etc.):
export PATH="$PATH":"$HOME/.pub-cache/bin"
Activated flutterfire_cli 0.2.7.
% export PATH="$PATH":"$HOME/.pub-cache/bin"
% flutterfire configure
i Found 2 Firebase projects.
✔ Select a Firebase project to configure your Flutter application with · auth-tutorial-44c9e (auth-tutorial)
✔ Which platforms should your configuration support (use arrow keys & space to select)? · android, ios, macos, web
i Firebase android app com.example.auth registered.
i Firebase ios app com.example.auth registered.
...
```프로젝트 개요 옆 톱니바퀴(프로젝트 설정)을 눌러 아래로 스크롤 하면 각 앱을 설정할 수 있도록 하는 창이 있습니다.
google-services.json을 다운로드해서 ./android/app/google-services.json에 내용을 채워줍니다.
./android/app/build.gradle
plugins {
id "com.android.application"
id "kotlin-android"
id "dev.flutter.flutter-gradle-plugin"
id 'com.google.gms.google-services' // 추가!
}
..../android/build.gradle
buildscript {
ext.kotlin_version = '1.7.10'
ext.google_services_version = '4.3.15' // 추가!
...
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.gms:google-services:$google_services_version" // 추가!
}
}마지막으로 SHA-1, SHA-256을 입력해줘야 합니다. 이를 위해서는 우선 java가 깔려있어야 합니다. MAC 사용자라면 아래 명령어를 순서대로 따라하면 됩니다.
brew install openjdk
echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
java -version // 잘 설치 되었는지 확인
keytool -list -v \
-alias androiddebugkey -keystore ~/.android/debug.keystore
(이후 나오는 인증서 지문 활용)여기서 나온 SHA-1, SHA-256을 입력해줍니다.
3. 구현 확인
구글 아이콘을 누르면 client 단에서는 signInWithGoogle() 함수가 실행되며, 팝업 화면으로 기존 구글 계정과 연동할 수 있게 해줍니다.
그간의 코딩과 세팅이 무색하게(?) 아이디를 터치하면 바로 회원가입이 완료됩니다.
Firebase Authentication에도 가입 여부가 잘 뜨는군요!
세팅이 많아 어려운 듯 보이지만, 시간 자체는 그렇게 오래걸리지 않았습니다. 중구난방으로 작성한 제 포스트가 보기 힘드시다면, 아래 참고사이트를 알려드리니 차근차근 해보세요.
참고 사이트
Flutter Client + OAuth2 구현 튜토리얼(Mitch Koko) https://www.youtube.com/playlist?list=PLlvRDpXh1Se4Ceivpg8KrGvzb8BL9BHwo
Firebase 공식 문서 https://firebase.google.com/docs/flutter/setup?hl=ko&platform=android
Android 앱에 Firebase 추가 https://firebase.google.com/docs/android/setup?hl=ko
Firebase Authentication https://firebase.google.com/docs/auth/flutter
Google Sign-In for Flutter https://pub.dev/packages/google_sign_in
클라이언트 인증(SHA-1 디지털 서명) https://developers.google.com/android/guides/client-auth?authuser=0&hl=ko