Sample code for 30+ languages & platforms
Swift

Twitter OAuth1 Authorization (3-legged)

See more OAuth1 Examples

Demonstrates 3-legged OAuth1 authorization for Twitter.

This example is deprecated and no longer valid.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    var consumerKey: String? = "TWITTER_CONSUMER_KEY"
    var consumerSecret: String? = "TWITTER_CONSUMER_SECRET"

    var requestTokenUrl: String? = "https://api.twitter.com/oauth/request_token"
    var authorizeUrl: String? = "https://api.twitter.com/oauth/authorize"
    var accessTokenUrl: String? = "https://api.twitter.com/oauth/access_token"

    // The port number is picked at random. It's some unused port that won't likely conflict with anything else..
    var callbackUrl: String? = "http://localhost:3017/"
    var callbackLocalPort: Int = 3017

    // The 1st step in 3-legged OAuth1.0a is to send a POST to the request token URL to obtain an OAuth Request Token
    let http = CkoHttp()!

    http.oAuth1 = true
    http.oAuthConsumerKey = consumerKey
    http.oAuthConsumerSecret = consumerSecret

    let req = CkoHttpRequest()!
    req.addParam(name: "oauth_callback", value: callbackUrl)

    req.httpVerb = "POST"
    req.contentType = "application/x-www-form-urlencoded"

    let resp = CkoHttpResponse()!
    success = http.httpReq(url: requestTokenUrl, request: req, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    // If successful, the resp.BodyStr contains something like this:  
    // oauth_token=-Wa_KwAAAAAAxfEPAAABV8Qar4Q&oauth_token_secret=OfHY4tZBX2HK4f7yIw76WYdvnl99MVGB&oauth_callback_confirmed=true
    print("\(resp.bodyStr!)")

    if resp.statusCode.intValue != 200 {
        print("Failed response status code: \(resp.statusCode.intValue)")
        return
    }

    let hashTab = CkoHashtable()!
    hashTab.addQueryParams(queryParams: resp.bodyStr)

    var requestToken: String? = hashTab.lookupStr(key: "oauth_token")
    var requestTokenSecret: String? = hashTab.lookupStr(key: "oauth_token_secret")
    http.oAuthTokenSecret = requestTokenSecret

    print("oauth_token = \(requestToken!)")
    print("oauth_token_secret = \(requestTokenSecret!)")

    // ---------------------------------------------------------------------------
    // The next step is to form a URL to send to the authorizeUrl
    // This is an HTTP GET that we load into a popup browser.
    let sbUrlForBrowser = CkoStringBuilder()!
    sbUrlForBrowser.append(value: authorizeUrl)
    sbUrlForBrowser.append(value: "?oauth_token=")
    sbUrlForBrowser.append(value: requestToken)
    var url: String? = sbUrlForBrowser.getAsString()

    // Launch the system's default browser navigated to the URL.
    let oauth2 = CkoOAuth2()!
    success = oauth2.launchBrowser(url: url)
    if success == false {
        print("\(oauth2.lastErrorText!)")
        return
    }

    // When the url is loaded into a browser, the response from Twitter will redirect back to localhost:3017
    // We'll need to start a socket that is listening on port 3017 for the callback from the browser.
    let listenSock = CkoSocket()!

    var backLog: Int = 5
    success = listenSock.bindAndListen(port: callbackLocalPort, backlog: backLog)
    if success == false {
        print("\(listenSock.lastErrorText!)")
        return
    }

    // Wait for the browser's connection in a background thread.
    // (We'll send load the URL into the browser following this..)
    // Wait a max of 60 seconds before giving up.
    let sock = CkoSocket()!
    var maxWaitMs: Int = 60000
    var task: CkoTask? = listenSock.acceptNextAsync(maxWaitMs: maxWaitMs, socket: sock)
    task!.run()

    // Wait for the listenSock's task to complete.
    success = task!.wait(maxWaitMs: maxWaitMs)
    if !success || (task!.statusInt.intValue != 7) || (task!.taskSuccess != true) {
        if !success {
            // The task.LastErrorText applies to the Wait method call.
            print("\(task!.lastErrorText!)")
        }
        else {
            // The ResultErrorText applies to the underlying task method call (i.e. the AcceptNextConnection)
            print("\(task!.status!)")
            print("\(task!.resultErrorText!)")
        }

        task = nil
        return
    }

    // If we get to this point, the connection from the browser arrived and was accepted.

    // We no longer need the listen socket...
    // Stop listening on port 3017.
    listenSock.close(maxWaitMs: 10)

    task = nil

    // Read the start line of the request..
    var startLine: String? = sock.receive(untilMatch: "\r\n")
    if sock.lastMethodSuccess == false {
        print("\(sock.lastErrorText!)")
        return
    }

    // Read the request header.
    var requestHeader: String? = sock.receive(untilMatch: "\r\n\r\n")
    if sock.lastMethodSuccess == false {
        print("\(sock.lastErrorText!)")
        return
    }

    // The browser SHOULD be sending us a GET request, and therefore there is no body to the request.
    // Once the request header is received, we have all of it.
    // We can now send our HTTP response.
    let sbResponseHtml = CkoStringBuilder()!
    sbResponseHtml.append(value: "<html><body><p>Chilkat thanks you!</b></body</html>")

    let sbResponse = CkoStringBuilder()!
    sbResponse.append(value: "HTTP/1.1 200 OK\r\n")
    sbResponse.append(value: "Content-Length: ")
    sbResponse.appendInt(value: sbResponseHtml.length.intValue)
    sbResponse.append(value: "\r\n")
    sbResponse.append(value: "Content-Type: text/html\r\n")
    sbResponse.append(value: "\r\n")
    sbResponse.appendSb(sb: sbResponseHtml)

    sock.sendString(str: sbResponse.getAsString())
    sock.close(maxWaitMs: 50)

    // The information we need is in the startLine.
    // For example, the startLine will look like this:
    //  GET /?oauth_token=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd HTTP/1.1
    let sbStartLine = CkoStringBuilder()!
    sbStartLine.append(value: startLine)
    var numReplacements: Int = sbStartLine.replace(value: "GET /?", replacement: "").intValue
    numReplacements = sbStartLine.replace(value: " HTTP/1.1", replacement: "").intValue
    sbStartLine.trim()

    // oauth_token=abcdRQAAZZAAxfBBAAABVabcd_k&oauth_verifier=9rdOq5abcdCe6cn8M3jabcdj3Eabcd
    print("startline: \(sbStartLine.getAsString()!)")

    hashTab.clear()
    hashTab.addQueryParams(queryParams: sbStartLine.getAsString())

    requestToken = hashTab.lookupStr(key: "oauth_token")
    var authVerifier: String? = hashTab.lookupStr(key: "oauth_verifier")

    // ------------------------------------------------------------------------------
    // Finally , we must exchange the OAuth Request Token for an OAuth Access Token.

    http.oAuthToken = requestToken
    http.oAuthVerifier = authVerifier

    // We don't need the "Authorization: OAuth ..." header for this POST.
    http.oAuth1 = false
    req.removeParam(name: "oauth_callback")
    req.addParam(name: "oauth_verifier", value: authVerifier)
    req.addParam(name: "oauth_token", value: requestToken)

    req.httpVerb = "POST"
    req.contentType = "application/x-www-form-urlencoded"

    success = http.httpReq(url: accessTokenUrl, request: req, response: resp)
    if success == false {
        print("\(http.lastErrorText!)")
        return
    }

    // Make sure a successful response was received.
    if resp.statusCode.intValue != 200 {
        print("\(resp.statusLine!)")
        print("\(resp.header!)")
        print("\(resp.bodyStr!)")
        return
    }

    // If successful, the resp.BodyStr contains something like this:
    // oauth_token=85123455-fF41296Bi3daM8eCo9Y5vZabcdxXpRv864plYPOjr&oauth_token_secret=afiYJOgabcdSfGae7BDvJVVTwys8fUGpra5guZxbmFBZo&user_id=85612355&screen_name=chilkatsoft&x_auth_expires=0
    print("\(resp.bodyStr!)")

    hashTab.clear()
    hashTab.addQueryParams(queryParams: resp.bodyStr)

    var accessToken: String? = hashTab.lookupStr(key: "oauth_token")
    var accessTokenSecret: String? = hashTab.lookupStr(key: "oauth_token_secret")
    var userId: String? = hashTab.lookupStr(key: "user_id")
    var screenName: String? = hashTab.lookupStr(key: "screen_name")

    // The access token + secret is what should be saved and used for
    // subsequent REST API calls.
    print("Access Token = \(accessToken!)")
    print("Access Token Secret = \(accessTokenSecret!)")
    print("user_id = \(userId!)")
    print("screen_name  = \(screenName!)")

    // Save this access token for future calls.
    // Just in case we need user_id and screen_name, save those also..
    let json = CkoJsonObject()!
    json.appendString(name: "oauth_token", value: accessToken)
    json.appendString(name: "oauth_token_secret", value: accessTokenSecret)
    json.appendString(name: "user_id", value: userId)
    json.appendString(name: "screen_name", value: screenName)

    let fac = CkoFileAccess()!
    fac.writeEntireTextFile(path: "qa_data/tokens/twitter.json", fileData: json.emit(), charset: "utf-8", includePreamble: false)

    print("Success.")

}