Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update addKeychainItem(...) to improve compatibility with FaceID #193

Merged
merged 1 commit into from
May 21, 2024

Conversation

crysxd
Copy link

@crysxd crysxd commented May 14, 2024

This PR improves the way addKeychainItem(...) distinguishes between adding and updating an item when used with FaceID. The original implementation caused two operations on the key chain:

  1. Check if key exists
  2. Update or add

This caused two consecutive FaceID prompts for the user. The new implementation attempts to add the item but then checks for errSecDuplicateItem. This error occurs before the FaceID prompt is shown. If the operation fails with this specific error we proceed to update the item, causing a FaceID prompt.

To use KeychainSettings with FaceID, you can use this snippet:

fun <T> withBiometricSettings(
      service: String,
      reason: String,
      block: KeychainSettings.() -> T
): T {
    val context = LAContext().apply {
        localizedReason = reason
    }

    val settings = KeychainSettings(
        kSecAttrService to CFBridgingRetain(service),
        kSecUseAuthenticationContext to interpretCPointer(context.objcPtr()),
        kSecAttrAccessControl to SecAccessControlCreateWithFlags(
            kCFAllocatorDefault,
            kSecAttrAccessibleWhenUnlockedThisDeviceOnly as CFTypeRef,
            1UL shl 3, // biometryCurrentSet
            null
        ),
    )

    return block(settings)
}

withBiometricSettings(reason = "Login") {
   getStringOrNull(key = "secret")
}
    ```

@russhwolf russhwolf changed the base branch from main to 1.2 May 21, 2024 03:41
@russhwolf
Copy link
Owner

Thanks. I'm going to tweak this a little but the general idea makes sense.

@russhwolf russhwolf merged commit 962db69 into russhwolf:1.2 May 21, 2024
3 of 4 checks passed
@crysxd
Copy link
Author

crysxd commented May 21, 2024

Amazing! Thank you!
Any rough ETA for the 1.2 release? I now copied the class into our source code with my modifications.

I use your library in all my projects btw, it's a real life saver 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants