Keychain Access Control TouchID with password fallback
suggest changeKeychain can save items with a SecAccessControl attribute so that an item can be read only after the user is authenticated. .userPresence accepts biometry (Touch ID or Face ID) or the device passcode. It is not an app-specific password. The app is only notified whether authentication succeeded. The whole UI is managed by iOS.
First, SecAccessControl object should be created:
Swift
var error: Unmanaged<CFError>?
guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, .userPresence, &error) else {
fatalError("Something went wrong")
}
error has to be a var so its address can be passed. On failure it may describe why creation failed; this sample stops without reading it.
Next, add it to the dictionary with kSecAttrAccessControl key (which is mutually exclusive with kSecAttrAccessible key you’ve been using in other examples):
Swift
var dictionary = [String : Any]()
dictionary[kSecClass as String] = kSecClassGenericPassword
dictionary[kSecAttrLabel as String] = "com.me.myapp.myaccountpassword" as CFString
dictionary[kSecAttrAccount as String] = "My Name" as CFString
dictionary[kSecValueData as String] = "new_password!!".data(using: .utf8) as! CFData
dictionary[kSecAttrAccessControl as String] = accessControl
And save it as you’ve done before:
Swift
let lastResultCode = SecItemAdd(dictionary as CFDictionary, nil)
To access stored data, query the Keychain for the item. Keychain Services presents an authentication dialog and returns the data or nil depending on whether biometry or the device passcode succeeded.
Optionally, prompt string can be specified:
Swift
var query = [String: Any]()
query[kSecClass as String] = kSecClassGenericPassword
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecAttrAccount as String] = "My Name" as CFString
query[kSecAttrLabel as String] = "com.me.myapp.myaccountpassword" as CFString
query[kSecUseOperationPrompt as String] = "Please put your fingers on that button" as CFString
var queryResult: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &queryResult)
noErr means success. A declined, canceled, or failed authentication comes back as another status, such as errSecUserCanceled or errSecAuthFailed, not as a value named err.
Swift
if status == noErr {
let password = String(data: queryResult as! Data, encoding: .utf8)!
print("Password: \(password)")
} else {
print("Authorization not passed")
}
as! CFData and as! Data crash if the value is missing or is not data, and String’s force-unwrapped result crashes if the bytes are not UTF-8.