iOS KeyChain not retrieving values from background iOS KeyChain not retrieving values from background ios ios

iOS KeyChain not retrieving values from background


My question was close to the mark for the reason why, but not quite. After reading through blog after blog, tutorial after tutorial, I finally found one that gave off a hint of what might be happening.

Locked home screens. The keychain tutorials always left the accessibility settings for the keychain blank, so it would default to Apple's lowest/safest access level. This level however doesn't allow keychain access if the user has a passcode on the lock screen. Bingo! This explains the sporadic behavior and why this only happens to a small percentage of users.

One line of code, solves the entire mess.

[wrapper setObject:(__bridge id)kSecAttrAccessibleAlways forKey:(__bridge id)kSecAttrAccessible];

Add this line where I'm setting the username and password values. Works like a charm. Hope this will help someone out there. It confounded me for quite a while until I was able to put the pieces together.


Use kSecAttrAccessibleAfterFirstUnlock instead of kSecAttrAccessibleAlways.


From Apple's documentation:

kSecAttrAccessibleAfterFirstUnlock
The data in the keychain item cannot be accessed after a restart until the device has been unlocked once by the user.

After the first unlock, the data remains accessible until the next restart. This is recommended for items that need to be accessed by background applications. Items with this attribute migrate to a new device when using encrypted backups.


In my case, watchOS2 accesses keychain data on the iOS side.

At the beginning, kSecAttrAccessibleWhenUnlockedThisDeviceOnly is used. I can read the data no matter iPhone is locked or not. It is very confusing to me that I will receive Error when watch is trying to access the keychain:: SecTrustEvaluate [leaf IssuerCommonName SubjectCommonName]

And some case it will become:: SecOSStatusWith error:[-25308] Error Domain=NSOSStatusErrorDomain Code=-25308 "ks_crypt: e00002e2 failed to 'oe' item (class 6, bag: 0) Access to item attempted while keychain is locked." UserInfo={NSDescription=ks_crypt: e00002e2 failed to 'oe' item (class 6, bag: 0) Access to item attempted while keychain is locked.}

I will update my answer if I get more infos.