我正在尝试使用 NetworkExtension 框架在 Mac OSX 上实现 IKEv2 vpn 连接。每次我得到一个弹出窗口来输入我的 vpn 连接密码。根据 NEVPNProtocol 规范,可以通过提供存储在钥匙串中的密码的持久引用来提供密码。但它不起作用。我在 iOS 中尝试过相同的 IKEv2 配置代码,它运行良好。
我编写了一个示例应用程序来演示我是如何做到的 - https://github.com/kestutisbalt/osx-ikev2-sample
密码如何存储在钥匙串中:
class func set(key: String, value: String) {
let query: [NSObject: AnyObject] = [
kSecValueData: value.dataUsingEncoding(NSUTF8StringEncoding)!,
kSecClass: kSecClassGenericPassword,
kSecAttrGeneric: key,
kSecAttrAccount: key,
kSecAttrAccessible: kSecAttrAccessibleAlways,
kSecAttrService: NSBundle.mainBundle().bundleIdentifier!
]
clear(key)
SecItemAdd(query as CFDictionaryRef, nil)
}
如何从钥匙串中检索持久引用:
class func persistentRef(key: String) -> NSData? {
let query: [NSObject: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrGeneric: key,
kSecAttrAccount: key,
kSecAttrAccessible: kSecAttrAccessibleAlways,
kSecMatchLimit: kSecMatchLimitOne,
kSecAttrService: NSBundle.mainBundle().bundleIdentifier!,
kSecReturnPersistentRef: kCFBooleanTrue
]
var secItem: AnyObject?
let result = SecItemCopyMatching(query, &secItem)
if result != errSecSuccess {
return nil
}
return secItem as? NSData
}
IKEv2 配置:
private func createIKEv2Protocol(host: String,
username: String, password: String) -> NEVPNProtocolIKEv2 {
Keychain.set(username, value: password)
let passwordRef = Keychain.persistentRef(username)
if passwordRef == nil {
log("Failed to query password persistent ref")
}
let config = NEVPNProtocolIKEv2()
config.remoteIdentifier = host
config.serverAddress = host
config.useExtendedAuthentication = true
config.username = username
config.passwordReference = passwordRef
return config
}