Search code examples
swiftfacebook-graph-apihttp-status-code-403

Swift: Facebook Graph API not accepting valid access_token


I'm running a swift script from the command line on a mac. I'm simply trying to post a url with an access_token that I verified works in other browsers. Facebook won't accept the post. I'm using the URLSession in swift and not the Facebook SDK.

guard let url = URL(string: "https://graph.facebook.com/aumuaamata?") else { return }
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)

var request = URLRequest(url: url)
request.httpMethod = "POST"

let postString = "access_token=433263852003213|gLKD8g4ZAlADEDSSKqy8u_KZ_0"
request.httpBody = postString.data(using: .utf8)

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

let runLoop = CFRunLoopGetCurrent()
let task = session.dataTask(with: request, completionHandler: { data, response, error in
     if error == nil {
         print("it works!")
     } else {
         print("task error: \(error!)")
     }
     CFRunLoopStop(runLoop)
})
task.resume()
CFRunLoopRun()

Facebook responds with A page access token is required to request this resource and insufficient_scope.

I tried adding the access_token to the URL and then encoding it like this:

guard let escapedUrlString = urlRawString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) else { return }

But the script won't run and says it's not a valid URL. Typed into a browser everything works as it should.

Any ideas?


Solution

  • This is the fix. I tried it with curl and had the same issue.

    request.httpMethod = "GET"
    request.setValue("Bearer 433263852003213|gLKD8g4ZAlADEDSSKqy8u_KZ_0", forHTTPHeaderField: "Authorization")
    

    Seems odd that this is necessary but it works!

    And no, the example token I posted is not valid (probably).