问题描述
我将 Moya 用于 iOS 网络。
我们的服务器(在虚拟机上)使用 OAuth,并且需要使用访问令牌发出请求。
我正在尝试使用 POST /oauth/token
检索我们端点的初始访问令牌。
我要回来的是:
此服务器的证书无效。您可能正在连接到一个伪装成“xxxxxx”的服务器,这可能会使您的机密信息处于危险之中。”您仍要连接到该服务器吗?
VM 不验证证书。
这可能是问题吗?
如果是这样,Moya 应该如何配置以忽略证书验证?
如果没有,关于如何为此目的使用 Moya 的任何想法?
以下是 Moya 配置:
enum MyApi {
case auth
}
extension MyApi: targettype {
var baseURL: URL {
return URL(string: "https://server.nb/apI/Oauth/token")!
}
var path: String {
return ""
}
var method: Moya.Method {
return .post
}
var sampleData: Data {
return Data()
}
var task: Task {
let params = [
"client_id": "xxxxxxx","client_secret": "xxxxxxxx","grant_type": "password","password": "xxxxxxxx","username": "niv@bp.com"
]
return .requestParameters(parameters: params,encoding: URLEncoding.default)
}
var headers: [String : String]? {
let headers = [
"Content-Type": " application/x-www-form-urlencoded",]
return headers
}
}
编辑:
这是 info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>https://server.nb</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
</dict>
这是 Moya 提供程序服务:
struct MoyaNetworkService {
private let moyaProvider: MoyaProvider<MyApi>!
init(moyaProvider: MoyaProvider<MyApi> = MoyaProvider<MyApi>()) {
self.moyaProvider = moyaProvider
}
func auth() {
moyaProvider.request(.auth) { (result) in
}
}
}
解决方法
extension ServerTrustPolicy {
static let defaultTrustPolicy: ServerTrustPolicy = .pinPublicKeys(
publicKeys: ServerTrustPolicy.publicKeys(),validateCertificateChain: true,validateHost: true
)
static let noEvaluationPolicy: ServerTrustPolicy = .disableEvaluation <== this is what you need
}
fileprivate lazy var trustPolicies: [String: ServerTrustPolicy] = {
var trustPolicies = [String :ServerTrustPolicy]()
trustPolicies["your_host_sans_https"] = .noEvaluationPolicy
return trustPolicies
}()
fileprivate let manager = Manager (
configuration: alamofireConfiguration,serverTrustPolicyManager: ServerTrustPolicyManager(policies: trustPolicies)
)
func getProvider() -> MoyaProvider<MyApi> {
let provider = MoyaProvider<MyApi>(manager : manager)
return provider
}
,
问题出在需要证书的虚拟机上。 这是有关如何设置的技术问答链接。我选择使用我们的 VPN。 https://developer.apple.com/library/archive/qa/qa1948/_index.html