dbconfession
dbconfession

Reputation: 1199

Swift 2 How do you add authorization header to POST request

When making a particular POST request, Firefox (FF) dev tools shows a req. header named "Authorization" with a value of "Bearer X" where X is the access token received upon login. When I edit this request in FF and remove the "Authorization" line, I get a 400 error. When I put it back in, 200 and all is well. I haven't yet, however, figured out how to set this request header programmatically without getting 400.

Also, FF tools as a "Request Body" of {"source":"desktop - profile 2015"}. I'm assuming this is JSON. I've tried posting this in several ways (see code) but have had no success.

// the following fields are set in the object "Request"'s initialization
let accessToken = "1,2,3456789012,3x4f560fa7a89e01a2;33ab4b4e5e67e8e9b9f0e1a23db45678f9a9a0ff" // replaced some characters for this StackOF posting
let authorization = "Bearer \(accessToken)"
let method = "POST"
let userID = "1234567"
let URL = NSURL(string: "https://www.somesite.com/apitun/profile/\(userID)hide")

// tried setting params to all of the following 4:
let params = ""
let params = "&_json={}"
let params = "&_json={\"source\":\"desktop profile - 2015\"}
let params = "&_json=%7B%22source%22%3A%22desktop%2Dprofile%202015%22%7D"

func execute() {
    let session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: URL)
    if authorization != "" {
        request.addValue(authorization, forHTTPHeaderField: "Authorization")
    }

    request.HTTPMethod = self.method
    request.HTTPBody = self.params.dataUsingEncoding(NSUTF8StringEncoding)
    self.task = session.dataTaskWithRequest(request) {
        (data, response, error) in
        NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(self.cookies, forURL: self.URL, mainDocumentURL: nil)
        if error == nil {
            do {
                self.responseHeaders = response as! NSHTTPURLResponse
                self.cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(self.URL)!
                self.statusCode = self.responseHeaders.statusCode

                switch self.statusCode {

                case 200:
                    self.contentsOfURL = try NSString(contentsOfURL: self.URL, encoding: NSUTF8StringEncoding)
                case 400:
                    print("400: page not found")

                case 404:
                    print("404: page not found")

                case 407:
                    print("407: failed authenticate proxy credentials")

                default:
                    print("unable to get statusCode")

                }
            } catch {

            }
            self.isRequesting = false
        } else {
            print(error)
        }
    }
    self.task.resume()
}   

Upvotes: 6

Views: 10267

Answers (1)

ThE uSeFuL
ThE uSeFuL

Reputation: 1534

let request = NSMutableURLRequest(URL: NSURL(string: fullURL)!)

let accessToken = "your access token"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")

Upvotes: 24

Related Questions