Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
}   
like image 426
dbconfession Avatar asked May 27 '16 03:05

dbconfession


People also ask

How do I request a post with Authorization header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

How do I send a POST request with Bearer Token Authorization header?

To send a POST JSON request with a Bearer Token authorization header, you need to make an HTTP POST request, provide your Bearer Token with an Authorization: Bearer {token} HTTP header and give the JSON data in the body of the POST message.

How do I add Authorization to a header for fetch request?

You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter.

How do I add auth token in header?

The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.


1 Answers

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

let accessToken = "your access token"
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
like image 140
ThE uSeFuL Avatar answered Nov 15 '22 10:11

ThE uSeFuL