Twitterizer: Solving the 401 bug when calling "GetAccessToken" or "GetRequestToken"
I recently encountered a strange bug using the Twitterizer API. I couldn’t call “GetAccessToken” without getting a 401 error. After searching about it, I found out that other people encountered the same bug by calling the “GetRequestToken” method (see more info here). The correct way to get an access token using the twitterizer API is using the following source code sequence:
OAuthTokenResponse requestAccessTokens = OAuthUtility.GetRequestToken(Properties.Settings.Default.ConsumerKey, Properties.Settings.Default.ConsumerSecret, "oob"); requestToken = requestAccessTokens.Token; String twitterPinURL = OAuthUtility.BuildAuthorizationUri(requestAccessTokens.Token).AbsoluteUri; //The user inputs the Pin number that he read from the URL in the previous step OAuthTokenResponse accessTokens = OAuthUtility.GetAccessToken(Properties.Settings.Default.ConsumerKey, Properties.Settings.Default.ConsumerSecret, requestToken, pinNumber);
The source code above may crash on the last line. The bug is probably caused by wrong timestamps, Twitter is sensitive to server time inaccuracies. The rash of issues lately is apparently caused by the clocks on Twitter’s servers being off by a small amount. First check your system’s time, if it is correct you can try to add a delay of 10-15 seconds before calling the “GetAccessToken” method. I managed to fix the issue in my desktop application by calling a Thread.Sleep() call. The revised code is shown below:
OAuthTokenResponse requestAccessTokens = OAuthUtility.GetRequestToken(Properties.Settings.Default.ConsumerKey, Properties.Settings.Default.ConsumerSecret, "oob"); requestToken = requestAccessTokens.Token; String twitterPinURL = OAuthUtility.BuildAuthorizationUri(requestAccessTokens.Token).AbsoluteUri; //The user inputs the Pin number that he read from the URL in the previous step Thread.Sleep(10000); OAuthTokenResponse accessTokens = OAuthUtility.GetAccessToken(Properties.Settings.Default.ConsumerKey, Properties.Settings.Default.ConsumerSecret, requestToken, pinNumber);