Flutter Andorid GCP Google Login (without Firebase)

Cafelatte·2025년 6월 6일

Flutter

목록 보기
1/1

References

Environment

  • ndkVersion: 27.0.12077973
  • minSdk: 23
  • google_sign_in: ^6.3.0

방법

1. Flutter 프로젝트 생성하기

flutter create login_test

2. 인증키 생성하기

  • 인증키를 아래와 같은 명령어로 생성한 후 android/app/ 폴더에 저장합니다.
# keytool 명령어는 자바가 설치되어있어야 합니다.
keytool -genkey -v -keystore debug.keystore -alias debug -keyalg RSA -keysize 2048 -validity 10000

3. 인증키 정보 확인 및 등록하기

  • android/ 폴더로 이동 후 아래와 같은 명령어를 통해 출력된 내용에서 2번에서 생성된 인증키가 제대로 인식되는지 확인합니다.
  • 출력된 내용 중 생성된 인증키의 SHA-1 키값을 따로 복사해 둡니다.
gradlew.bat signingReport
  • android/app/build.gradle.kts 파일 내 인증키 정보를 아래와 같이 등록합니다.
  • 비밀번호는 직접 설정한 값을 입력해야 합니다.
android {
...
    signingConfigs {
        getByName("debug") {
            storeFile = file("debug.keystore")
            storePassword = "000000"
            keyAlias = "debug"
            keyPassword = "000000"
        }
        ...
    }

    buildTypes {
        debug {
            signingConfig = signingConfigs.getByName("debug")
        }
        ...
    }
...
}

4. GCP 클라이언트 생성하기

  • 데이터 액세스탭에서 아래와 같이 범위를 등록합니다. (id_token과 관련된 범위는 openid)
  • 그 다음 클라이언트 총 두 개를 생성해야 합니다. 첫 번째로 안드로이드용 클라이언트를 생성합니다.
  • 3번에서 복사해 둔 SHA-1 값과 아래의 파일에서 패키지 이름을 찾아 입력 한 후 생성합니다.
// android\app\build.gradle.kts
...
    defaultConfig {
        applicationId = "com.example.login_test" // 패키지 이름
        minSdk = 23
        targetSdk = flutter.targetSdkVersion
        versionCode = flutter.versionCode
        versionName = flutter.versionName
    }
...
  • 두 번째로 웹용 클라이언트를 생성합니다.
  • 웹용 클라이언트는 별도의 정보를 입력할 필요없이 생성을 마친 후, 클라이언트 ID를 복사해 둡니다.

INFO: 안드로이드용 클라이언트를 등록하지 않으면 로그인 자체가 안되고, 웹용 클라이언트를 등록하지 않으면 id_token을 가져오지 못합니다.

5. 구글 로그인 기능 구현하기

  • 테스트용 구글 로그인 기능을 구현합니다.
  • 특히 GoogleSignIn 객체를 초기화할 때 'serverClientId' 파라미터에 4번 마지막에 복사해 둔 웹용 클라이언트 ID를 입력해야 합니다.

IMPORTANT: 안드로이드용 클라이언트 ID 아님

...
    final GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: ['openid', 'email', 'profile'],
      serverClientId:
          '<웹용 클라이언트 ID>',
    );
...

lib/main.dart

import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: const OnBoarding(),
    );
  }
}

class OnBoarding extends StatefulWidget {
  const OnBoarding({super.key});

  
  State<OnBoarding> createState() => _OnBoardingState();
}

class _OnBoardingState extends State<OnBoarding> {

  
  void initState() {
    super.initState();
  }

  Future<void> _signIn() async {
    final GoogleSignIn googleSignIn = GoogleSignIn(
      scopes: ['openid', 'email', 'profile'],
      serverClientId:
          '<웹용 클라이언트 ID>',
    );
    final GoogleSignInAccount? googleUser = await googleSignIn.signIn();
    final GoogleSignInAuthentication? googleAuth =
        await googleUser?.authentication;
    print("email: ${googleUser?.email}");
    print("accessToken: ${googleAuth?.accessToken}");
    print("idToken: ${googleAuth?.idToken}");
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(onPressed: _signIn, child: Text('Sign In')),
      ),
    );
  }
}

테스트 하기

  • 에뮬레이터 혹은 개인 디바이스를 통해 로그인 버튼을 누를 시 id_token을 잘 가져오는지 확인합니다.
# terminal1: 구동
flutter run
#terminal2: 로그 (해당 터미널에서 id_token 확인)
flutter logs
profile
바로 활용 가능한 정보 공유를 목적으로 합니다

0개의 댓글