I'm trying to connect to a vpn using Swift. I have created class VpnHandler and I'm using Keychain Swift to keep keychain reference.
My code look like this:
import Foundation
import NetworkExtension
import KeychainSwift
final class VPNHandler {
let vpnManager = NEVPNManager.shared()
func initVPNTunnelProviderManager(serverAdress: String, remoteIdentifier : String, sharedSecred:String) {
let sharedKey = sharedSecred.data(using: .utf8)
let keychain = KeychainSwift()
guard let sharedKey = sharedKey else { return }
keychain.set(sharedKey, forKey: "shared_secret")
vpnManager.loadFromPreferences { error in
if let error = error {
print(error.localizedDescription)
return
}
let IKEv2Protocol = NEVPNProtocolIKEv2()
IKEv2Protocol.username = nil
IKEv2Protocol.localIdentifier = nil
IKEv2Protocol.serverAddress = serverAdress
IKEv2Protocol.remoteIdentifier = remoteIdentifier
IKEv2Protocol.authenticationMethod = .sharedSecret
IKEv2Protocol.disconnectOnSleep = false
IKEv2Protocol.useExtendedAuthentication = false
IKEv2Protocol.sharedSecretReference = keychain.getData("shared_secret", asReference: true)
IKEv2Protocol.passwordReference = nil
var rules = [NEOnDemandRule]()
let rule = NEOnDemandRuleConnect()
rule.interfaceTypeMatch = .any
rules.append(rule)
self.vpnManager.localizedDescription = "My VPN"
self.vpnManager.protocolConfiguration = IKEv2Protocol
self.vpnManager.onDemandRules = rules
self.vpnManager.isOnDemandEnabled = true
self.vpnManager.isEnabled = true
print("SAVE TO PREFERENCES...")
self.vpnManager.saveToPreferences { error in
if (error != nil) {
print(error!)
return
}
print("CALL LOAD TO PREFERENCES AGAIN...")
self.vpnManager.loadFromPreferences { error in
if let error = error {
print(error.localizedDescription)
return
}
do {
try self.vpnManager.connection.startVPNTunnel()
print("Starting VPN...")
} catch let error {
print("can't connect VPN'")
print(error.localizedDescription)
}
}
}
}
}
}
When I call the function initVPNTunnelProviderManager, the vpn configuration in the phone setting is created. Our app starting connecting to vpn, but then disconnect immediately. When we connect vpn configuration in the phone setting, it's working.
I don't know what the problem is.
Any help is appreciated.
Thanks in advance
I just solved the issue. In your server in /etc/ipsec.conf file, replace the following: