AND4011002849
AND4011002849

Reputation: 2001

401 alamofire get request with headers

I'm getting error 401 trying to make a request using custom headers, when I print the headers, it is there, just like I make a call using postman, the difference is that in postman the request works, but in the app I get that error, I don't think it is the headers, because as I said they are there, what am I missing here?

func getUserByID(completion: @escaping CompletionHandler) {
        let url_id = URL_USER_ID + String(self.userID)

        let header:HTTPHeaders = [
            "Content-Type": "application/json",
            "Authorization": "Token " + AuthService.instance.authToken
        ]

        Alamofire.request(url_id, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: header).responseJSON{
            (response) in

            guard let data = response.data else {return}
            let json = try? JSON(data: data)

            if response.response?.statusCode == 200 {

                let user = json!["user"]
                let id = user["id"].stringValue
                let email = user["email"].stringValue
                let img = user["img"].stringValue
                let tipo_usuario = user["tipo_usuario"].intValue
                let nome_comp = user["nome_comp"].stringValue
                let end_cep = user["end_cep"].stringValue
                let end_logr = user["end_logr"].stringValue
                let end_num = user["end_num"].stringValue
                let end_bairro = user["end_bairro"].stringValue
                let end_complm = user["end_complm"].stringValue
                let cidade = user["cidade"]
                let cidadeID = cidade["id"].intValue
                let cidadeNome = cidade["nome"].stringValue
                let cidadeEstado = cidade["estado"].stringValue
                let telefone = user["telefone"].stringValue
                let whatsapp = user["whatsapp"].stringValue
                let pontos = user["pontos"].intValue
                let cnpj_cpf = user["cnpj_cpf"].stringValue
                let razao_social = user["razao_social"].stringValue
                let nome_fantasia = user["nome_fantasia"].stringValue
                let insc_estadual = user["insc_estadual"].stringValue
                let categoria = user["categoria"].intValue
                let nota = user["nota"].stringValue

                let cidadeUser = Cidades(id: cidadeID, nome: cidadeNome, estado: cidadeEstado)
                UserDataService.instance.setUserData(id: id, email: email, img: img, tipo_usuario: tipo_usuario, nome_comp: nome_comp, end_cep: end_cep, end_logr: end_logr, end_num: end_num, end_bairro: end_bairro, end_complm: end_complm ,cidade: cidadeUser, telefone: telefone, whatsapp: whatsapp, pontos: pontos, cnpj_cpf: cnpj_cpf, razao_social: razao_social, nome_fantasia: nome_fantasia, insc_estadual: insc_estadual, categoria: categoria, nota: nota)

                self.userEmail = email
                self.userID = Int(id)!

                completion(true)
            } else if response.response?.statusCode == 400 {
                completion(false)
            } else {
                debugPrint(response.result.error as Any)
            }
        }
    }enter code here

and the error message:

Error=-25300, query={
    atyp = http;
    class = inet;
    "m_Limit" = "m_LimitAll";
    ptcl = http;
    "r_Attributes" = 1;
    sdmn = "api.ddns.net";
    srvr = "api.ddns.net";
    sync = syna;
}
$ curl -v \
    -H "Content-Type: application/json" \
    -H "Accept-Language: en;q=1.0, pt-BR;q=0.9" \
    -H "Authorization: Token 4e97e608c72636052583a1bb1c170485417a739b" \
    -H "User-Agent: clubelocal/1.0 (com.api; build:1; iOS 11.2.0) Alamofire/4.7.0" \
    -H "Accept-Encoding: gzip;q=1.0, compress;q=0.5" \
    "http://api.ddns.net:8000/users/25"
Optional({
  "detail" : "the user credentials was not provided."
})

Upvotes: 1

Views: 1555

Answers (1)

blaszku
blaszku

Reputation: 299

I faced similar issue like:

Postman performed request with success, but alamofire with 401 JWT Token not found. So the response was a failure, but server performed action for the request like it was success.

In my case it turned out to be redirection.

You should check if it is not due to redirection, because by default Alamofire doesn't pass authorization field in header to redirected request (this seems to be reasonable behavior in such case).

So to make authorization transmissible you can do it like:

Alamofire.SessionManager.default.delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
    var redirectedRequest = request

    if let originalRequest = task.originalRequest,
        let headers = originalRequest.allHTTPHeaderFields,
        let authorizationHeaderValue = headers["Authorization"]
    {
        var mutableRequest = request
        mutableRequest.setValue(authorizationHeaderValue, forHTTPHeaderField: "Authorization")
        redirectedRequest = mutableRequest
    }

    return redirectedRequest
}

//now use your requests  i.e:
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: header)
    .validate()
    .responseJSON(completionHandler: { (response) in
        switch response.result {
        case .success:
            //success
            break
        case .failure(let error):
            //fail
            break
        }
    })

If you want to return to default behavior just simply:

Alamofire.SessionManager.default.delegate.taskWillPerformHTTPRedirection = nil

Upvotes: 3

Related Questions