I am trying to do implement signing in with twitter account in golang. I am the first step where in I am trying to get the request token. As a reference I used the mrjones's code available at below link. https://github.com/mrjones/oauth/blob/master/examples/twitterserver/twitterserver.go
I am getting following error. Please let me know where am I going wrong:
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
var twitterConf = &TwitterConfig{
ClientID: " my consumer key",
ClientSecret: "my consumer key secret",
RedirectURL: "http://localhost:8080/oauth/twitterOauth2callback",
Endpoint: ServiceProvider{
RequestTokenUrl: "https://api.twitter.com/oauth/request_token",
AuthorizeTokenUrl: "https://api.twitter.com/oauth/authorize",
AccessTokenUrl: "https://api.twitter.com/oauth2/token",
},
}
func HandletwitterLogin(res http.ResponseWriter, req *http.Request, _ httprouter.Params) {
ctx := appengine.NewContext(req)
params := url.Values{}
params.Add(CALLBACK_PARAM, twitterConf.RedirectURL)
params.Add(CONSUMER_KEY_PARAM, twitterConf.ClientID)
params.Add(NONCE_PARAM, strconv.FormatInt(rand.New(rand.NewSource(time.Now().UnixNano())).Int63(), 10))
params.Add(SIGNATURE_METHOD_PARAM, SIGNATURE_METHOD_HMAC+"SHA1")
params.Add(TIMESTAMP_PARAM, strconv.FormatInt(time.Now().Unix(), 10))
params.Add(VERSION_PARAM, OAUTH_VERSION)
params.Add("oauth_token", "my oauth token")
baseString := requestString("POST", twitterConf.Endpoint.RequestTokenUrl, params)
signature, err6 := Sign(baseString, "my token secret")
params.Add(SIGNATURE_PARAM, signature)
Url, err := url.Parse(twitterConf.Endpoint.RequestTokenUrl)
Url.RawQuery = params.Encode()
firsturl := Url.String()
reqnew, err2 := http.NewRequest("POST", firsturl, nil)
if err2 != nil {
log.Errorf(ctx, "ERROR IN CREATING NEW REQUEST %+v ", err2)
}
reqnew.Header.Add("Authorization", "OAuth ")
client := urlfetch.Client(ctx)
resp, err3 := client.Do(reqnew)
if err3 != nil {
log.Errorf(ctx, "ERROR IN doing the client request %+v ", err3)
}
bodyBytes, err4 := ioutil.ReadAll(resp.Body)
resp.Body.Close()
log.Infof(ctx, "HandletwitterLogin 5 ")
if err4 != nil {
log.Errorf(ctx, "ERROR IN READALL RESP BODY %+v ", err4)
}
bodyStr := string(bodyBytes)
//Here i am getting above mentioned error
}
These are the other functions which I used.
func requestString(method string, url string, params url.Values) string {
result := method + "&" + escape(url)
for key, value := range params {
if len(value) > 0 {
result += escape("&")
result += escape(fmt.Sprintf("%s=%s", key, value))
}
}
return result
}
func Sign(message string, tokenSecret string) (string, error) {
key := escape(twitterConf.ClientSecret) + "&" + escape(tokenSecret)
h := hmac.New(crypto.SHA1.New, []byte(key))
h.Write([]byte(message))
rawSignature := h.Sum(nil)
base64signature := base64.StdEncoding.EncodeToString(rawSignature)
return base64signature, nil
}
See Question&Answers more detail:
os