首页 > 解决方案 > 使用 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
        }
    }
}

标签: iosswiftsslaccess-tokenmoya

解决方案


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
}

推荐阅读