【问题标题】:How to make a request using Token in the header and basic authentication in Alamofire?如何使用标头中的 Token 和 Alamofire 中的基本身份验证发出请求?
【发布时间】:2018-07-16 10:21:20
【问题描述】:

我需要向我自己的 API 发出请求,而后端人员在发出请求时需要基本身份验证,而且我必须将令牌放在标头中。我在向 API 发出请求时使用的是 Alamofire。

这是 postman 中的基本身份验证

这是标头中的 X-API-KEY 令牌

但我不知道如何在标头中同时实现基本身份验证和 X-API-KEY 令牌。以前,如果仅使用下面的代码使用基本身份验证,我可以发送请求,但我不知道如何在使用 alamofire 发出请求时要求它们(标头中的基本身份验证和 X-API-KEY 令牌)都需要;

let urlSendDefect = URLService.defects.endPoint
let username = "admin"
let password = "1234"

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: username, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}

let parameters : [String:Any] = ["defect_id": defectID, "defect_comment" : comment, "status" : status]

Alamofire.request(urlSendDefect,
                  method: .put,
                  parameters: parameters,
                  encoding: URLEncoding.default,
                  headers:headers)
    .validate()
    .responseJSON { response in

        switch response.result {

        case .failure(let error) :

            print("Error while making request to send defect comment to server: \(error.localizedDescription)")
            completion(nil,error)

        case .success(let value) :

            let json = JSON(value)
            if let message = json["message"].string {

                if message.isEmpty {
                    completion(nil,nil)
                } else {
                    completion(message,nil)
                }

            } else {
                completion(nil,nil)
            }


        }        
}

【问题讨论】:

    标签: ios json swift httprequest alamofire


    【解决方案1】:

    你能试着这样构造吗

    let headers : HTTPHeaders = ["Content-Type":"application/json",
                                 "Authorization":"Basic \(Your_token)"]
    

    并添加您想要的任何其他键值

    【讨论】:

    • 是否需要使用Basic,`Bearer`..etc来传递token?
    • 我必须使用什么密钥来插入用户名和密码以进行基本身份验证?从这个线程stackoverflow.com/questions/35494157/…看来,它也使用了“Authorization”:“Basic”键值对
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 2016-05-04
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 2022-08-07
    相关资源
    最近更新 更多