我正在使用 django rest framework for apis 开发一个 iOS 应用程序。但目前我无法在使用身份验证凭据调用 api 时取得成功。
我通过将 Header 设置为 Authentication Bearer <token>
成功地使用 Postman 和 curl 调用了 api ..但我一直无法从 iOS 应用程序调用它。我正在使用 Moya
用于调用 api。而且我不知道下一步该做什么。
我尝试了什么:(调用 Moya 时)
let token = "abcde12345sometoken"
let plugin = AccessTokenPlugin(tokenClosure: token)
let provider = MoyaProvider<AccountAPI>(plugins : [plugin])
provider.request(.getAccountProfile(oauth_id: oauth_id, provider: "facebook")) { (result) in
// doing something with result
}
并将 API 配置为:
extension AccountAPI : TargetType, AccessTokenAuthorizable {
// codes conforming variables to TargetType protocol
public var authorizationType: AuthorizationType {
switch self {
case .getFacebookAccountToken:
return .none
default:
return .bearer
}
}
public var headers: [String: String]? {
switch self {
case .getFacebookAccountToken, .getEmailAccountToken: // post requests
return ["Content-type":"application/x-www-form-urlencoded"]
default:
return ["Content-type":"application/json"]
}
}
}
在使用 Moya 进行身份验证或使用 Info.plist 等时,有什么我应该考虑的吗? 或者文档说这种方法适用于 JWT token ,也许我的方法不适用于 JWT 和其他东西..?给我一些建议!
最佳答案
对于我的情况,我使用
Moya
12.0.1
多目标
例子:
plugins = [AccessTokenPlugin(tokenClosure: {
let token = ...
return token
})]
MoyaProvider<MultiTarget>(
plugins: plugins
)
.request(MultiTarget(myAPI)) {
...
}
但它从不调用 tokenClosure
解决方案 你需要添加这个扩展
extension MultiTarget: AccessTokenAuthorizable {
public var authorizationType: AuthorizationType {
guard let target = target as? AccessTokenAuthorizable else { return .none }
return target.authorizationType
}
}
来源:https://github.com/Moya/Moya/blob/master/Sources/Moya/Plugins/AccessTokenPlugin.swift#L62
关于ios - Moya - 无法使用身份验证凭据调用 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46356132/