Dav*_*tti 29 keychain ios touch-id swift
我正在努力实现以下代码:
我看了钥匙扣和身份验证与Touch ID演示,并了解以下内容:
如果在向Keychain中添加新值时设置了正确的参数,则下次尝试将其取出时,系统将自动显示Touch 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);
Run Code Online (Sandbox Code Playgroud)
起初我认为模拟器有一些问题,但没有,我能够使用以下代码检查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");
}
Run Code Online (Sandbox Code Playgroud)
我还能够使用以下代码以编程方式显示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");
}
});
Run Code Online (Sandbox Code Playgroud)
Touch ID有效,但是将值保存到Keychain并带有标志以强制系统本身触摸ID不起作用 - 我缺少什么?
Apple提供的名为KeychainTouchID的示例:将Touch ID与Keychain和LocalAuthentication一起使用也会显示不一致的结果,并且系统不会强制执行Touch ID.
Mar*_*n R 23
仅当您SecItemCopyMatching()
在后台队列上呼叫时,才会显示"触摸ID"弹出窗口.这在Keychain和带有Touch ID的身份验证的PDF演示文稿的第118页上
显示:
读一个秘密
......Run Code Online (Sandbox Code Playgroud)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`
}
Run Code Online (Sandbox Code Playgroud)
并且类似地用于更新和删除.
以下是示例代码的组合版本,其中包含必要的后台队列调度以检索钥匙串项.(当然,必须将UI更新分派回主队列.)
它在我使用Touch ID的iPhone测试中按预期工作:出现Touch 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).")
}
}
}
Run Code Online (Sandbox Code Playgroud)