当用户退出时,我想从我的服务中删除钥匙串值。但是,我对最佳实践方法感到困惑。
这是我的服务
let userAccount = "AuthenticatedUser"
let accessGroup = "SecuritySerivice"
let passwordKey = "KeyForPassword"
let kSecClassValue = NSString(format: kSecClass)
let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
let kSecValueDataValue = NSString(format: kSecValueData)
let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
let kSecAttrServiceValue = NSString(format: kSecAttrService)
let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
let kSecReturnDataValue = NSString(format: kSecReturnData)
let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)
public class KeychainService: NSObject {
public class func savePassword(token: String) {
self.save(service: passwordKey, data: token)
}
public class func loadPassword() -> String? {
return self.load(service: passwordKey)
}
public class func removePassword() {
}
private class func save(service: String, data: String) {
let dataFromString: Data = data.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue), allowLossyConversion: false)!
let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, dataFromString], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])
SecItemDelete(keychainQuery as CFDictionary)
SecItemAdd(keychainQuery as CFDictionary, nil)
}
private class func load(service: String) -> String? {
let keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])
var dataTypeRef :AnyObject?
// Search for the keychain items
let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
var contentsOfKeychain: String? = nil
if status == errSecSuccess {
if let retrievedData = dataTypeRef as? Data {
contentsOfKeychain = String(data: retrievedData, encoding: String.Encoding.utf8)
}
} else {
print("KEY: Nothing was retrieved from the keychain. Status code \(status)")
}
return contentsOfKeychain
}
private class func remove(service: String) {
}
}
显然,我是不是应该删除任何形式的钥匙串
答案 0 :(得分:0)
您可以清除数据。请尝试以下行
keychain["yourKey"] = nil
或
do {
try keychain.remove("yourKey")
} catch let error {
print("error: \(error)")
}
由于
答案 1 :(得分:0)
如果要使用KeychainItemWrapper删除项目,请使用-resetKeychainItem。这会使SecItemDelete()调用正确的值。
答案 2 :(得分:0)
要删除钥匙串使用中的用户名密码
func removeUserFromKeychain() {
let spec: NSDictionary = [kSecClass: kSecClassGenericPassword]
SecItemDelete(spec)
}