ios - 使用 Moya for iOS 从服务器获取访问令牌
问题描述
我正在将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
}
推荐阅读
- arrays - 从数组中查找最接近数字的函数始终返回数组的第一个元素
- python - Django在分页中保持相同的过滤器
- reactjs - React Hook "useEffect" 被有条件地调用,在所谓的简单的 get-display-retrieve 输入组件中
- masstransit - MassTransit 调度程序使用者不更新普罗米修斯指标
- xsd - 我可以从 Microsoft Graph 中的 openTypeExtension 获取结构 XSD 架构吗
- typescript - 设置 typescript 以使用 require 和 import 语法
- url - 您可以更改 Google Cloud Storage 上文件的公共 URL 吗?
- c# - 发送电子邮件时 D365 插件错误 0x80040265
- python - 为什么我在 python 中得到一个无效的语法错误?
- nginx - Nginx Tracing 无法进入上游服务