[Flutter] 자동로그인 구현하기 with Flutter Keychain

kimdocs...📄·2023년 12월 1일
0

flutter

목록 보기
24/30

개요

iOS에서 사용하는 Keychain 방식으로 개발하기 위해 몇가지 문서를 찾아보았다. (키체인 - 앱을 지웠다가 깔아도 사용자 정보를 저장하고 있어 바로 로그인 시킬 수 있다는 장점이 있다) 그러던 중!! flutter_keychain패키지 문서에서 이런 문구를 발견했다.

⚠️ A Flutter plugin for supporting secure storage of strings via Keychain and Keystore If you have other types you want to store, you need to serialize to and from UTF-8 strings.
  • Keychain is used for iOS.
  • AES encryption is used for Android. AES secret key is encrypted with RSA and RSA key is stored in KeyStore

Note KeyStore was introduced in Android 4.3 (API level 18). The plugin does not work on earlier versions.

아하? iOS는 키체인 방식을 사용하지만, Android는 AES encryption을 사용한다고 한다.

Android 4.3 이전 버전에서는 동작하지 않을 수 있으니 확인할 것! 그치만 2012년 버전인 API level18은 고려하지 않기로 하고 flutter_keychain을 사용하기로 결정했다.


패키지 설치

flutter pub add flutter_keychain

pubspec.yaml에 아래 줄이 생성됐는 지 확인

dependencies:
  flutter_keychain: ^2.4.0

import하여 사용

import 'package:flutter_keychain/flutter_keychain.dart';

안드로이드는 최소 버전 지정

[project]/android/app/build.gradle 에서 minSdkVersion 18로 설정하면 됨

android {
    ...
    defaultConfig {
        ...
        minSdkVersion 18
        ...
    }
}

사용 예시

import 'package:flutter_keychain/flutter_keychain.dart';
...

// Get value
var value = await FlutterKeychain.get(key: "key");

// Put value
await FlutterKeychain.put(key: "key", value: "value");

// Remove item
await FlutterKeychain.remove(key: "key");

// Clear the secure store
await FlutterKeychain.clear();

flutter_keychain | Flutter Package


활용

keychain_key.dart 파일 생성

키값을 상수로 가지고 있는 클래스

class KeychainKey {
  static String id = "id";
  static String pw = "pw";
}

auth_info_checker.dart

사용자의 계정 정보를 확인하는 클래스

class AuthInfoChecker {
  static const AuthInfoChecker shared = AuthInfoChecker._internal();

  const AuthInfoChecker._internal();

  Future<bool> isLoggedIn() async {
    var userId = await FlutterKeychain.get(key: KeychainKey.userPK);

    if (null == userId) {
      return false;
    }

    return true;
  }
}

사용자 id가 저장되어 있으면 자동으로 로그인, 아닐경우 로그인 화면으로 이동

저장하는 방법

int userPK = await _authRepository.signUp(userId, password, nickname);
await FlutterKeychain.put(key: KeychainKey.userPK, value: userPK.toString());
profile
👩‍🌾 GitHub: ezidayzi / 📂 Contact: ezidayzi@gmail.com

0개의 댓글