생체 인증 Biometric

quinones·2025년 6월 13일

안드로이드 앱에서 지문인식이나 얼굴 인식을 해주는 방식이 궁금해서 사용해봤다.

라이브러리 추가

biometric 라이브러리를 추가해준다.

implementation ("androidx.biometric:biometric:1.1.0")

전역 변수 추가

    private lateinit var executor: Executor // 인증 콜백 실행 스레드 관리
    private lateinit var biometricPrompt: BiometricPrompt // 생체 인증 dialog 생성 및 관리
    private lateinit var promptInfo: BiometricPrompt.PromptInfo // 인증 dialog 정보

초기화

사용하는 화면의 onCreate 혹은 onViewCreated에서 초기화 시켜준다.

// 1. Executor 초기화: 인증 콜백을 메인(UI) 스레드에서 실행하도록 설정
executor = ContextCompat.getMainExecutor(this)
// 2. BiometricPrompt 초기화: 생체 인증 객체 생성 및 콜백 정의
biometricPrompt = BiometricPrompt(this, executor,
object : BiometricPrompt.AuthenticationCallback() {
    override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
        super.onAuthenticationSucceeded(result)
        // 인증 성공 시 로직 (예: 다음 작업 진행)
        Log.i("BIOMETRIC_TAG", "인증 성공!")
    }
    override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
        super.onAuthenticationError(errorCode, errString)
        // 오류 발생 시 로직 (예: 사용자에게 메시지 표시)
        Log.e("BIOMETRIC_TAG", "인증 오류: $errString (코드: $errorCode)")
    }
    override fun onAuthenticationFailed() {
        super.onAuthenticationFailed()
        // 인증 실패 시 로직 (예: 재시도 안내)
        Log.w("BIOMETRIC_TAG", "인증 실패")
    }
})

// 3. PromptInfo 초기화: 인증 대화상자에 표시될 정보 설정
promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("생체 인증")
.setSubtitle("기기에 등록된 생체 정보를 사용해 인증해주세요.")
.setNegativeButtonText("취소")
.build()

원하는 위치에서 사용

예를 들어 어떤 버튼 클릭 시 생체 인증을 사용할거라면 이렇게 인증을 시작해준다.
결과는 초기화 했던 코드에서 성공/오류/실패를 오버라이딩한 부분에서 처리해준다.

button.setOnClickListener {
    // 5. 생체 인증 대화상자 표시
    biometricPrompt.authenticate(promptInfo)
}
profile
이우진

0개의 댓글