Alamofire 未创建身份验证标头来发送凭据
Posted
技术标签:
【中文标题】Alamofire 未创建身份验证标头来发送凭据【英文标题】:Alamofire not creating autnentication header to send credentials 【发布时间】:2020-08-19 07:41:51 【问题描述】:我正在尝试使用我的用户名和 api 密钥访问 api。他们给出的一个例子,我相信是 .NET,是:
Public Sub GET_Products()
Dim request As HttpWebRequest = WebRequest.Create("https://api.ssactivewear.com/v2/products/?style=39")
request.Method = "GET"
request.Credentials = New NetworkCredential("YOurCustomerNumber", "YourAPIKey")
Try
Dim response As HttpWebResponse = request.GetResponse
Dim StreamReader As New StreamReader(response.GetResponseStream())
Result = StreamReader.ReadToEnd
If response.StatusCode = HtppStatusCode.OK Then
Products = serializer.Deserialize(Of List(Of Sku))(Result)
Else
End If
Catch ex As Exception
End Try
End Sub
我已使用以下内容来测试响应请求:
guard let url = URL(string: "https://api.ssactivewear.com/v2/products/") else return
let username = "myusername"
let password = "myapikey"
AF.request(url).authenticate(username: username, password: password).responseJSON response in
print("Request: \(String(describing: response.request))")
print("Response: \(String(describing: response.response))")
print("HeaderFields: \(String(describing: response.request?.allHTTPHeaderFields))")
if let json = response.value
print("JSON: \(json)")
//self.responseText.text = "JSON: \(json)"
if let error = response.error
print("ERROR: \(error.localizedDescription)")
//self.responseText.text = "ERROR: \(error.localizedDescription)"
验证失败,因为没有发送验证标头。我相信我读到这是预期的行为,但没有找到解决方案。
【问题讨论】:
【参考方案1】:创建API中类:
class APIManager
class func headers() -> HTTPHeaders
let headers: HTTPHeaders = [
"Content-Type": "application/json",
"Accept": "application/json"
]
return headers
您的 api 调用:
let request = AF.request(path, method: .post, parameters: params, encoding: JSONEncoding.default, headers: APIManager.headers(), interceptor: nil)
request.responseDecodable(of: UserModel?.self) (resposnse) in
let user = resposnse.value
print(user)
【讨论】:
【参考方案2】:Alamofire 的authenticate
方法将URLCredential
添加到用于响应服务器挑战的Request
。如果服务器从不为这些凭据发送质询,则永远不会使用这些凭据。 api.ssactivewear.com
似乎使用 HTTP Basic auth,它应该可以正常工作,但我找不到任何关于此的特定文档。正确地向 API 发出请求可能还有其他要求。我建议您调查这些要求以及发送的实际网络流量,以了解实际发生的情况。
【讨论】:
以上是关于Alamofire 未创建身份验证标头来发送凭据的主要内容,如果未能解决你的问题,请参考以下文章
djangorestframework-jwt 未提供身份验证凭据