0

I need to make a request to my own API, and the backend guy requires basic authentication when making request and also I have to put the token in the header. I am using Alamofire when making request to the API.

here is the basic authentication in postman

enter image description here

and here is the X-API-KEY token in the header

enter image description here

but I don't know how to implement both of basic auth and X-API-KEY token in the header. previously I can send request if just using basic authentication using the code below, But i have no idea how to make a request if both of them (Basic authentication and X-API-KEY token in the header) are required when making request using alamofire;

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)
            }


        }        
}
Johan Kool
  • 15,637
  • 8
  • 64
  • 81
sarah
  • 3,819
  • 4
  • 38
  • 80

1 Answers1

1

Can you try to construct it like this

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

and add any other key-value that you want

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • do we need to use `Basic`, ` Bearer` ..etc to pass token? – Wings Jul 16 '18 at 10:33
  • what is the key that I have to use to insert username and password for basic authentication? from this thread https://stackoverflow.com/questions/35494157/basic-authentication-with-alamofire it seems that it also uses "Authorization":"Basic " key value pair – sarah Jul 16 '18 at 22:36