只能在Swift 3中使用Touch ID访问Keychain中的数据

时间:2016-11-29 18:58:00

标签: ios swift keychain touch-id

我正致力于实现以下代码的和平:

  • 将一些数据存储在Keychain中。
  • 仅在用户使用Touch ID或Pass Code进行身份验证时才获取数据。

我观看了Keychain and Authentication with Touch ID演示并理解了以下内容:

  

如果您在向钥匙串添加新值时设置了正确的参数,则下次   你试着把它拿出来,系统会自动显示出来   触摸ID弹出窗口。

我写了一些代码,但我的假设并不奏效。这就是我写的:

    //
    //  Secret value to store
    //
    let valueData = "The Top Secret Message V1".data(using: .utf8)!;

    //
    //  Create the Access Controll object telling how the new value
    //  should be stored. Force Touch ID by the system on Read.
    //
    let sacObject =
        SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                            kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
                            .userPresence,
                            nil);

    //
    //  Create the Key Value array, that holds the query to store 
    //  our data
    //
    let insert_query: NSDictionary = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrAccessControl: sacObject!,
        kSecValueData: valueData,
        kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow,
        //  This two valuse ideifieis the entry, together they become the
        //  primary key in the Database
        kSecAttrService: "app_name",
        kSecAttrAccount: "first_name"
    ];

    //
    //  Execute the query to add our data to Keychain
    //
    let resultCode = SecItemAdd(insert_query as CFDictionary, nil);

起初我认为模拟器有一些问题,但没有,我能够使用以下代码检查Touch ID是否存在:

    //
    //  Check if the device the code is running on is capapble of 
    //  finger printing.
    //
    let dose_it_can = LAContext()
        .canEvaluatePolicy(
            .deviceOwnerAuthenticationWithBiometrics, error: nil);

    if(dose_it_can)
    {
        print("Yes it can");
    }
    else
    {
        print("No it can't");
    }

我还能够使用以下代码以编程方式显示Touch ID弹出窗口:

    //
    //  Show the Touch ID dialog to check if we can get a print from 
    //  the user
    //
    LAContext().evaluatePolicy(
        LAPolicy.deviceOwnerAuthenticationWithBiometrics,
        localizedReason: "Such important reason ;)",
        reply: {
            (status: Bool, evaluationError: Error?) -> Void in

            if(status)
            {
                print("OK");
            }
            else
            {
                print("Not OK");
            }

    });

总结一下

Touch ID可以使用,但是将值保存到钥匙串中并带有强制触摸ID的标志,系统本身无法正常工作 - 我缺少什么?

苹果示例

Apple提供的名为KeychainTouchID: Using Touch ID with Keychain and LocalAuthentication的示例也显示不一致的结果,并且系统不会强制执行Touch ID。

技术规范

  • Xcode 8.1
  • Swift 3

1 个答案:

答案 0 :(得分:23)

仅当您拨打SecItemCopyMatching()时,才会显示Touch ID弹出窗口 在背景队列上。 这在PDF演示文稿的第118页上有说明 Keychain and Authentication with Touch ID

  

阅读秘密
  ......

dispatch_async(dispatch_get_global_queue(...), ^(void){
    CFTypeRef dataTypeRef = NULL;
    OSStatus status = SecItemCopyMatching((CFDictionaryRef)query,
                                     &dataTypeRef);
});

否则你阻止主线程而弹出窗口没有 出现。然后SecItemCopyMatching()失败(超时后) 错误代码-25293 = errSecAuthFailed

在您的示例项目中,失败并不会立即显现,因为 它在错误情况下打印错误的变量,例如

if(status != noErr)
{
    print("SELECT Error: \(resultCode)."); // <-- Should be `status`
}

,类似于更新和删除。

以下是必要的示例代码的组合版本 调度到后台队列以检索钥匙串项。 (当然,必须将UI更新分派回主队列。)

我在使用Touch ID的iPhone测试中按预期工作: 出现Touch ID弹出窗口,仅在之后检索钥匙串项目 验证成功。

触摸ID身份验证在iOS模拟器上运行。

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    //  This two values identify the entry, together they become the
    //  primary key in the database
    let myAttrService = "app_name"
    let myAttrAccount = "first_name"

    // DELETE keychain item (if present from previous run)

    let delete_query: NSDictionary = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrService: myAttrService,
        kSecAttrAccount: myAttrAccount,
        kSecReturnData: false
    ]
    let delete_status = SecItemDelete(delete_query)
    if delete_status == errSecSuccess {
        print("Deleted successfully.")
    } else if delete_status == errSecItemNotFound {
        print("Nothing to delete.")
    } else {
        print("DELETE Error: \(delete_status).")
    }

    // INSERT keychain item

    let valueData = "The Top Secret Message V1".data(using: .utf8)!
    let sacObject =
        SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                        kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
                                        .userPresence,
                                        nil)!

    let insert_query: NSDictionary = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrAccessControl: sacObject,
        kSecValueData: valueData,
        kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow,
        kSecAttrService: myAttrService,
        kSecAttrAccount: myAttrAccount
    ]
    let insert_status = SecItemAdd(insert_query as CFDictionary, nil)
    if insert_status == errSecSuccess {
        print("Inserted successfully.")
    } else {
        print("INSERT Error: \(insert_status).")
    }

    DispatchQueue.global().async {
        // RETRIEVE keychain item

        let select_query: NSDictionary = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: myAttrService,
            kSecAttrAccount: myAttrAccount,
            kSecReturnData: true,
            kSecUseOperationPrompt: "Authenticate to access secret message"
        ]
        var extractedData: CFTypeRef?
        let select_status = SecItemCopyMatching(select_query, &extractedData)
        if select_status == errSecSuccess {
            if let retrievedData = extractedData as? Data,
                let secretMessage = String(data: retrievedData, encoding: .utf8) {

                print("Secret message: \(secretMessage)")

                // UI updates must be dispatched back to the main thread.

                DispatchQueue.main.async {
                    self.messageLabel.text = secretMessage
                }

            } else {
                print("Invalid data")
            }
        } else if select_status == errSecUserCanceled {
            print("User canceled the operation.")
        } else {
            print("SELECT Error: \(select_status).")
        }
    }
}