iosswiftkeychain

How to delete iOS Keychain item from private keychain when using access groups?


I am using Keychain on iOS to store some data. The app has entitlement to a group.com.mycompany via the access group. I have added keychain item under key my_item_key in the app's private keychain container and also created an entry in the shared keychain container (via the access group). If I try to read by the key my_item_key from the private keychain, returns the value for the private one, the same if I try to read my_item_key from the shared access group keychain it returns proper value that was stored under the shared one.

But, if I try to delete the item with key my_item_key in the private keychain, it also deletes the keychain item in the shared container although I did not specify the access group.

deleting without specifying access group:

            let query: NSMutableDictionary = [
                kSecClass as String: kSecClassGenericPassword,
                kSecAttrAccount as String: "my_item_key",
                kSecAttrService as String: "com.mycompany.appOne",
            ]
            
            let status = SecItemDelete(query)
            print("delete status: \(status)")
// deletes keychain item from app private keychain and shared keychain.
// even without specifying kSecAttrAccessGroup

is this even possible? or deleting means deletion from both containers and I have to use different kSecAttrAccount keys ?


Solution

  • The dictionary you provide to SecItemDelete is a query; it searches for matching items and deletes them.

    You can use kSecAttrAccessGroup in your query dictionary to specify which keychain should be searched.

    Without this, all accessible keychains are searched.

    From the documentation

    By default, the SecItemUpdate(::), SecItemDelete(:), and SecItemCopyMatching(:_:) methods search all the app’s access groups. Add the kSecAttrAccessGroup attribute to the query to limit the search to a particular group.