Juan de la Torre
Juan de la Torre

Reputation: 1297

Twitter Application-only authentication always return 401

I am trying to authenticate using App only auth and I successfully get the bearer token but when I try to make calls to the REST APIs, I always get an 401 error, here is my code:

private var accessToken: String?
private let consumerKey = "*********"
private let consumerSecret = "*********"
private let baseUrlString = "https://api.twitter.com/1.1/"
private let pageSize = 20

private func authenticate(completionBlock: Void -> ()) {

    if accessToken != nil {
        completionBlock()
    }

    let credentials = "\(consumerKey):\(consumerSecret)"
    let headers = ["Authorization": "Basic \(credentials.getBase64())"]
    let params: [String : AnyObject] = ["grant_type": "client_credentials"]

    Alamofire.request(.POST, "https://api.twitter.com/oauth2/token", headers: headers, parameters: params)
        .responseJSON { response in
            if let JSON = response.result.value {
                self.accessToken = JSON.objectForKey("access_token") as? String
                completionBlock()
            }
    }
}

func getTimelineForScreenName(screenName: String) {

    authenticate {

        guard let token = self.accessToken else {
            // TODO: Show authentication error
            return
        }

        let headers = ["Authorization": "Bearer \(token.getBase64())"]
        let params: [String : AnyObject] = [
            "screen_name" : screenName,
            "count": self.pageSize
        ]
        Alamofire.request(.GET, self.baseUrlString + "statuses/user_timeline.json", headers: headers, parameters: params)
            .responseJSON { response in
                print(response.response)

                if let JSON = response.result.value {
                    print(JSON)
                }
        }
    }
}

...

private extension String {
    func getBase64() -> String {
        let credentialData = self.dataUsingEncoding(NSUTF8StringEncoding)!
        return credentialData.base64EncodedStringWithOptions([])
    }
}

I have tried generating new keys but nothing, also tried what's suggested in this bug found in iOS 9 not letting the Authorization header get passed on redirects but this request is not using any redirects.

Any ideas would be greatly appreciated.

Upvotes: 2

Views: 1125

Answers (1)

Juan de la Torre
Juan de la Torre

Reputation: 1297

After a few hours of investigation I found by fluke that the header with the Bearer Token shouldn't be encoded to base64, so the header should look something like this:
let headers = ["Authorization": "Bearer \(token)"].

I hope this helps anyone trying something similar because the documentation says you have to use a base64 encoded token.

Step 3: Authenticate API requests with the bearer token
The bearer token may be used to issue requests to API endpoints which support application-only auth. To use the bearer token, construct a normal HTTPS request and include an Authorization header with the value of Bearer <base64 bearer token value from step 2>. Signing is not required.

Upvotes: 7

Related Questions