Authenticate and Request a User's Timeline with Twitter API 1.1 Oauth

Authenticate and request a user's timeline with Twitter API 1.1 oAuth

Here is what I did to get this working in a simple example.

I had to generate an oAuth consumer key and secret from Twitter at:

https://dev.twitter.com/apps/new

I deserialized the authentication object first to get the token and type back in order to authenticate the timeline call.

The timeline call simply reads the json as that is all I need to do, you may want to deserialize it yourself into an object.

I have created a project for this at : https://github.com/andyhutch77/oAuthTwitterWrapper

Update - I have updated the github project to include both asp .net web app & mvc app example demos and nuget install.

// You need to set your own keys and screen name
var oAuthConsumerKey = "superSecretKey";
var oAuthConsumerSecret = "superSecretSecret";
var oAuthUrl = "https://api.twitter.com/oauth2/token";
var screenname = "aScreenName";

// Do the Authenticate
var authHeaderFormat = "Basic {0}";

var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey) + ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));

var postBody = "grant_type=client_credentials";

HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(oAuthUrl);
authRequest.Headers.Add("Authorization", authHeader);
authRequest.Method = "POST";
authRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
authRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

using (Stream stream = authRequest.GetRequestStream())
{
byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
stream.Write(content, 0, content.Length);
}

authRequest.Headers.Add("Accept-Encoding", "gzip");

WebResponse authResponse = authRequest.GetResponse();
// deserialize into an object
TwitAuthenticateResponse twitAuthResponse;
using (authResponse)
{
using (var reader = new StreamReader(authResponse.GetResponseStream())) {
JavaScriptSerializer js = new JavaScriptSerializer();
var objectText = reader.ReadToEnd();
twitAuthResponse = JsonConvert.DeserializeObject<TwitAuthenticateResponse>(objectText);
}
}

// Do the timeline
var timelineFormat = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={0}&include_rts=1&exclude_replies=1&count=5";
var timelineUrl = string.Format(timelineFormat, screenname);
HttpWebRequest timeLineRequest = (HttpWebRequest)WebRequest.Create(timelineUrl);
var timelineHeaderFormat = "{0} {1}";
timeLineRequest.Headers.Add("Authorization", string.Format(timelineHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token));
timeLineRequest.Method = "Get";
WebResponse timeLineResponse = timeLineRequest.GetResponse();
var timeLineJson = string.Empty;
using (timeLineResponse)
{
using (var reader = new StreamReader(timeLineResponse.GetResponseStream()))
{
timeLineJson = reader.ReadToEnd();
}
}


public class TwitAuthenticateResponse {
public string token_type { get; set; }
public string access_token { get; set; }
}

OAuth with httr package and twitter API v1.1

Try ... GET("https://api.twitter.com/1.1/statuses/home_timeline.json", sig) instead (substitute 1 by 1.1).

Get Twitter Home timeline without authentication(App only authentication)

App only authentication allow you to access resources from your application context. Not from a specific user account context (not even the account owning the app).

As you can see statuses/user_timeline.json?screen_name=zaheer6110 specifies the screen_name of the user you want to access to.

But the statuses/home_timeline.json endpoint is account specific. What it means is that it returns the tweet of the authenticated account. But as you are using Application only credentials, Twitter does not have any account to run the request against.

If you want to get a home timeline, you will have to authenticate with some user credentials (Access Token and Access Token Secret).

The account specific endpoints are specified in the documentation under Resource Information > Requires authentication. They are marked as Yes (user context only). You can find the documentation of HomeTimeline here.

You can generate a set of Access Tokens keys for your account on https://apps.twitter.com/app/

Twitter returns unauthorized for user timeline but not search

I've now resolved this, TL;DR: I needed to check my application and user Access levels matched in the Application Management panel and regenerate my access token/secret.

I get an HTTP401 response saying 'Not authorized.'

By comparing this to the API docs around Error Codes & Responses I saw that this had to be "Missing or incorrect authentication credentials".

I closely checked the Application Management panel of my app to check that I'd copied the keys/tokens/secrets correctly but also to see if there was any other discrepancies.

I noticed that my application Access Level was set to 'Read and write' but that my user's access token Access Level was only set to 'Read'.

By regenerating the Access token and secret on that page I was able to successfully retrieve my user timeline.

This doesn't make a huge amount of sense to me - given that both had the 'Read' access level originally I'm not sure why they need to match exactly, but it's fixed the problem.



Related Topics



Leave a reply



Submit