Search code examples
swifthttp-headersauthorizationalamofire

Can't send Authorization header with my request


I have a request endpoint for sylius API when I set the content-type header with application/json and the Authorization header with the exact value Bearer SampleToken through postman it responds fine with the intended response but when I try to set the request authorization header through URLRequest it gives me a response

{
"error" = "access_denied";
"error_description" = "OAuth2 authentication required";

}

when I monitor the request through charles I've noticed that the Authorization header is stripped off. I've tried many various ways to set the authorization header but with no luck.

func getTotalProducts(page:String){
let urlPath="https://demo.sylius.com/api/v2/taxons"
var request = URLRequest(url:  NSURL(string: urlPath)! as URL)
request.httpMethod = "GET"

request.setValue("Bearer SampleToken", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(request)
    .responseJSON { response in
        switch(response.result){
        case .success(let value):
            print(value)
            break
        case .failure(let error):
            print("something went wrong \(error.localizedDescription)")
        }
    }.session.finishTasksAndInvalidate()

}

The original postman request:


Solution

  • Since you're using Alamofire, why not simplify things?

    let url = "https://demo.sylius.com/api/v2/taxons"
    
        let headers: HTTPHeaders = [
            "Authorization": "Bearer SampleToken",
            "Accept": "application/json",
            "Content-Type": "application/json"
        ]
    
        Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: headers)
            .responseJSON { response in
                switch(response.result){
                case .success(let value):
                    print(value)
                    break
                case .failure(let error):
                    print("something went wrong \(error.localizedDescription)")
                }
            }.session.finishTasksAndInvalidate()