Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active November 25, 2022 08:24
Show Gist options
  • Save soffes/0f123d1117eaed885d3a40890ccaf070 to your computer and use it in GitHub Desktop.
Save soffes/0f123d1117eaed885d3a40890ccaf070 to your computer and use it in GitHub Desktop.
Easily access Shared Web Credentials
import Foundation
import Security
struct SharedWebCredentials {
// MARK: - Types
struct Credential {
let domain: String
let account: String
let password: String
init?(dictionary: NSDictionary) {
let dict = dictionary as Dictionary
guard let domain = dict[kSecAttrServer] as? String,
account = dict[kSecAttrAccount] as? String,
password = dict[kSecSharedPassword] as? String
else { return nil }
self.domain = domain
self.account = account
self.password = password
}
}
// MARK: - Accessing Credentials
static func get(domain domain: String? = nil, account: String? = nil, completion: (credential: Credential?, error: CFError?) -> Void) {
SecRequestSharedWebCredential(domain, account) { array, error in
let credential: Credential?
if let array = array as Array?, dictionary = array.first as? NSDictionary {
credential = Credential(dictionary: dictionary)
} else {
credential = nil
}
completion(credential: credential, error: error)
}
}
static func add(domain domain: String, account: String, password: String, completion: ((error: CFError?) -> Void)? = nil) {
SecAddSharedWebCredential(domain, account, password) { error in
completion?(error: error)
}
}
static func remove(domain domain: String, account: String, completion: ((error: CFError?) -> Void)? = nil) {
SecAddSharedWebCredential(domain, account, nil) { error in
completion?(error: error)
}
}
static func generatePassword() -> String? {
return SecCreateSharedWebCredentialPassword() as String?
}
}
@manas-sharma-1683
Copy link

Hey soffes, have you tried running SecAddSharedWebCredential on iOS 14? It fails on my device.

@manas-sharma-1683
Copy link

manas-sharma-1683 commented Dec 3, 2020

Update:
It works well on simulator regardless of the iOS version, but fails on real device with " failed to approve" error.
https://developer.apple.com/forums/thread/19441
https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_developer_associated-domains

@soffes
Copy link
Author

soffes commented Dec 5, 2020

Haven't used this in years, sorry.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment