[안드로이드 / Kotlin] 생체 인식 인증 사용하기

2022. 1. 7. 17:12·Android
반응형

앱에 민감한 정보나 고급 콘텐츠를 보호하기 위해 생체 인식 인증을 사용합니다. 안드로이드의 경우 지문을 이용한

생체 인식 인증을 사용하는데 해당 사용방법에 대해 알아보도록 하겠습니다.

 

1) 앱 지원 인증 유형 선택

 

기본적으로 앱에서 지원하는 인증 유형을 선택해야합니다. 구현하고자하는 지문인식의 경우

BiometricManager.Authenticators.BIOMETRIC_STRONG
// BiometricManager.Authenticators.BIOMETRIC_WEAK
// BiometricManager.Authenticators.DEVICE_CREDENTIAL

을 사용합니다. (DEVICE_CREDENTIAL의 경우 화면 잠금 사용자 인증 정보를 사용하는 인증 유형입니다.)

 

 

2) 생체 인식 인증 사용가능여부 판단

 

<소스코드>

private fun isSupportFingerPrint() : Boolean {
    val biometricManager = BiometricManager.from(this)
    
    when (biometricManager.canAuthenticate(BIOMETRIC_STRONG)) {
        BiometricManager.BIOMETRIC_SUCCESS ->
            return true
        BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE ->
            return false
        BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE ->
            return false
        BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED -> {
            /*// Prompts the user to create credentials that your app accepts.
            val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
                putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED,
                    BIOMETRIC_STRONG or DEVICE_CREDENTIAL)
            }
            startActivityForResult(enrollIntent, REQUEST_CODE)*/
        }
    }
    return false
}

BiometricManager를 사용하면 앱에서 생체 인식 인증 사용가능여부를 판단할 수 있습니다.

(BIOMETRIC_ERROR_NONE_ENROLLED가 불리면 ACTION_BIOMETRIC_ENROLL 인텐트 작업을 호출해서 지문 등록을 요구할 수 있습니다.)

 

 

3) 최종구현

 

<소스 코드>

biometricPrompt = BiometricPrompt(this, ContextCompat.getMainExecutor(this),
	object : BiometricPrompt.AuthenticationCallback() {
    	override fun onAuthenticationError(errorCode: Int,errString: CharSequence) {
        	super.onAuthenticationError(errorCode, errString)
            Snackbar.make(findViewById(R.id.main_title), "Authentication error: $errString", Snackbar.LENGTH_SHORT).show()
        }

        override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
            super.onAuthenticationSucceeded(result)
          	Snackbar.make(findViewById(R.id.main_title), "Authentication succeeded", Snackbar.LENGTH_SHORT).show()
        }

        override fun onAuthenticationFailed() {
        	super.onAuthenticationFailed()
			Snackbar.make(findViewById(R.id.main_title), "Authentication failed", Snackbar.LENGTH_SHORT).show()
        }
    })

promptInfo = BiometricPrompt.PromptInfo.Builder()
	.setTitle("title")
	.setSubtitle("subTitle")
	.setNegativeButtonText("use password")
	.build()

biometricPrompt.authenticate(promptInfo)

사용자가 생체 인증을 시도했을때 인증 결과를 받을 BiometricPrompt 객체를 먼저 선언합니다. 콜백의 구현은 BiometricPrompt.AuthenticationCallback을 이용하며

인증 에러시 onAuthenicationError(),

인증 성공시 onAuthenicationSucceeded(),

인증 실패시 onAuthenicationFailed()를 통해 콜백 받습니다.

 

사용자가 생체 인식을 할 수 있도록 화면을 구성해주기 위해 BiometricPrompt.PromptInfo 객체를 구현합니다.

(단, setNagtiveButtonText()와 setAllowedAuthenticators()는 함께 선언할 수 없습니다.)

authenticate()를 사용하면 생체 인식 인증을 사용자에게 보여줄 수 있습니다.

 

 

참고: http:// https://developer.android.google.cn/training/sign-in/biometric-auth?hl=ko#kotlin

 

반응형

'Android' 카테고리의 다른 글

[안드로이드 / Kotlin] RecyclerView에 대한 고찰  (0) 2022.01.22
[안드로이드 / Kotlin] Retrofit2  (0) 2022.01.15
[안드로이드 / Kotlin] 카카오 로그인 SDK v2 사용하기  (0) 2022.01.07
[안드로이드 / Kotlin] Int형을 Byte Array로 나타내기  (0) 2022.01.03
[안드로이드 / Kotlin] 블루투스 상태 체크  (0) 2021.12.11
'Android' 카테고리의 다른 글
  • [안드로이드 / Kotlin] RecyclerView에 대한 고찰
  • [안드로이드 / Kotlin] Retrofit2
  • [안드로이드 / Kotlin] 카카오 로그인 SDK v2 사용하기
  • [안드로이드 / Kotlin] Int형을 Byte Array로 나타내기
서주냥
서주냥
간단한 것도 기록하는 습관을 가지자
  • 서주냥
    DroidLog
    서주냥
  • 전체
    오늘
    어제
    • 전체보기 (58)
      • 알고리즘 (12)
        • 백준 (4)
        • 프로그래머스 (5)
        • 개념 (3)
      • Android (43)
        • Compose (1)
      • Java (2)
      • Kotlin (1)
  • 링크

    • GitHub
  • 인기 글

  • 태그

    클린 아키텍처
    Clean Architecture
    벨만 포드
    코틀린
    BLE
    알고리즘
    SnackBar
    moshi
    투 포인터
    ConstraintLayout
    최단 경로
    viewpager2
    textunit
    다이나믹 프로그래밍
    Hilt
    debounce
    안드로이드
    viewmodel
    뷰모델
    코루틴
    FusedLocationProviderClient
    자바
    프로그래머스
    Coroutine Flow
    백준
    이진 탐색
    RecyclerView
    블루투스
    reified
    Coroutine
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
서주냥
[안드로이드 / Kotlin] 생체 인식 인증 사용하기
상단으로

티스토리툴바