Last active
July 13, 2023 13:17
-
-
Save guillermo/cba5de22ab598b8e125fb00fb9fa0db5 to your computer and use it in GitHub Desktop.
twitter golang oauth2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package twitter allows to do twitter oauth2 calls with the standard oauth2 package | |
// I created this public gist after hours spent trying to find something that works. | |
// This is copy paste from production code, with all database and framework specifics removed by hand, | |
// so I don't know if it works "as is". | |
package twitter | |
var ( | |
TWITTER_CONFIG = &oauth2.Config{ | |
ClientID: ClientID, | |
ClientSecret: ClientSecret, | |
Endpoint: oauth2.Endpoint{ | |
// AuthURL: "https://twitter.com/i/oauth2/authorize", | |
AuthURL: "https://twitter.com/i/oauth2/authorize", | |
TokenURL: "https://api.twitter.com/2/oauth2/token", | |
AuthStyle: oauth2.AuthStyleInHeader, | |
}, | |
Scopes: []string{"tweet.read", "tweet.write", "users.read", "offline.access"}, | |
} | |
) | |
func twitter_redirect_url(host string) string { | |
return "https://" + host + "/networks/twitter/create" // That's just me | |
} | |
func genRedirectURL(w http.ResponseWriter, r *http.Request) { | |
state:= "Whatever you want back from twitter" // I use a base64 hmac to ensure the users does not modify it | |
url := TWITTER_CONFIG.AuthCodeURL(state, | |
oauth2.SetAuthURLParam("redirect_uri", twitter_redirect_url(r.Host)), | |
oauth2.SetAuthURLParam("code_challenge", "SOME_CODE_CHALLANGE"), | |
oauth2.SetAuthURLParam("code_challenge_method", "plain"), | |
) | |
} | |
func createToken(w http.ResposneWritter, r *http.Request) { | |
tok, err := TWITTER_CONFIG.Exchange(ctx, r.FormValue("code"), | |
oauth2.SetAuthURLParam("redirect_uri", twitter_redirect_url(r.Host)), | |
oauth2.SetAuthURLParam("code_verifier", "SOME_CODE_CHALLANGE"), | |
) | |
... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment