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?
}
}
@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