简体   繁体   中英

Can any one tell me why i am getting Bad authentication error while executing this code(Swift)?

I am using Fabric SDK to add the twitter login button in my app....... i add the authentication header in my URL but still it is showing Bad authentication error while executing. Suggest me how to add Header in the URL in Swift.

     let twitter = Twitter.sharedInstance()
    let oauthSigning = TWTROAuthSigning(authConfig:twitter.authConfig, authSession:twitter.session())

    let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()

    let request = NSMutableURLRequest(URL: NSURL(string: "https://api.twitter.com/1.1/search/tweets.json?q=Himan_dhawan")!)
    request.allHTTPHeaderFields = authHeaders
    println(request)
    var session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if((error) != nil) {
            println(error.localizedDescription)
        }

        var strData = NSString(data: data, encoding: NSASCIIStringEncoding)
        println(strData)
    })

    task.resume()

It's to do with the way that you're setting the headers on the request.

The Fabric doc's don't quite give you the full picture about creating the OAuth signing headers when wanting to use your own NSMutableURLRequest.

let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()

The return [NSObject : AnyObject]! dictionary gives you the values you need for the request. However, what it provides for the headers are different to what needs to be sent with the NSMutableURLRequest.

This is how you should be setting the headers for this request:

            let twitter = Twitter.sharedInstance()

            let oauthSigning = TWTROAuthSigning(authConfig:twitter.authConfig, authSession:twitter.session())

            let authHeaders = oauthSigning.OAuthEchoHeadersToVerifyCredentials()

            let mutableUrlWithUsableUrlAddress = NSMutableURLRequest(URL: usableUrlForRequest)

            mutableUrlWithUsableUrlAddress.addValue(authHeaders[TWTROAuthEchoAuthorizationHeaderKey] as? String, forHTTPHeaderField: "Authorization")

This sets the required Authorisation Key as a value for the "Authorization" header on the request, opposed to when you pass in the authHeaders dictionary, it gets set for "X-Verify-Credentials-Authorization".

The Fabric doc's do go into this, but it's slightly more tucked away than it should be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM