Search code examples
gooauth-2.0twitter-oauth

Can't get Oauth2 (Twitter) to work - returns invalid token


So I'm a bit of a newbie to Go, so excuse my ignorance. I'm trying to do a simple REST API call to twitter using oauth2 for an "application only" calls, but I keep getting "Invalid or expired token" back as an error.

Anyone have experience with setting something like this up?

Response is: {"errors":[{"code":89,"message":"Invalid or expired token."}]}

package main

import "fmt"
import "encoding/base64"
import "io/ioutil"
import "time"
import "golang.org/x/oauth2"

func main() {
    config := &oauth2.Config{
        Endpoint: oauth2.Endpoint{
            AuthURL: "https://api.twitter.com/oauth2/token",
            TokenURL: "https://api.twitter.com/oauth/request_token",
        },
    }
    accessToken := base64.StdEncoding.EncodeToString([]byte("{Consumer Key (API Key)}:{Consumer Secret (API Secret)}"));
    token := &oauth2.Token{
        AccessToken: accessToken, 
        Expiry: time.Now().Add(time.Duration(24)*time.Hour)
    }
    httpClient := config.Client(oauth2.NoContext, token)
    resp, err := httpClient.Get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=google")
    if (err != nil) {
        fmt.Printf("Error: %s", err)
    }
    defer resp.Body.Close();
    body, err :=  ioutil.ReadAll(resp.Body);
    if (err != nil) {
        fmt.Printf("Error: %s", err)
    }
    fmt.Printf("Access Token: %s\nToken: %s\nResponse: %s\n", accessToken, token, body)
}

Solution

  • So turned out I wasn't leveraging the client credentials oauth2 package. I was able to get it to work.

    Hope this helps someone in the future:

    package main
    
    import "fmt"
    import "io/ioutil"
    import "golang.org/x/oauth2"
    import "golang.org/x/oauth2/clientcredentials"
    
    func main() {
        config := &clientcredentials.Config{
            ClientID:     "{App Key}",
            ClientSecret: "{App Secret}",
            TokenURL:     "https://api.twitter.com/oauth2/token",
        }
        tok, err := config.Token(oauth2.NoContext)
        httpClient := config.Client(oauth2.NoContext)
        resp, err := httpClient.Get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=google")
        if (err != nil) {
            fmt.Printf("Error: %s", err)
        }
        defer resp.Body.Close();
        body, err :=  ioutil.ReadAll(resp.Body);
        if (err != nil) {
            fmt.Printf("Error: %s", err)
        }
        fmt.Printf("Access Token: %s\nToken: %s\nResponse: %s\n", tok, body)
    }