Search code examples
c#twitterservicestacklinq-to-twitter

Using Linq2Twitter and cached OAuth tokens withing a ServiceStack api


I want to use Linq2Twitter to make a Twitter API call from within a REST API written in ServiceStack.

I have the following information:

  • ConsumerKey
  • ConsumerSecret
  • cached OAuth Token from when the user authenticated our app on the site
  • cached OAuth TokenSecret from when the user authenticated our app on the site

How do I create the TwitterContext using this information so that I can make API calls? I am looking at the documentation and I see WebForm, MVC, Desktop examples, but none for my current use case. I don't think I can use the WebForm/MVC ones as those will try to redirect the user to an authorization page if the token/token secret are bad. I looked at the desktop example and it uses a pin authorization, which I don't think I can use either.

I understand that the token/token secret may be bad if the user decides to revoke access after I have cached these values, so I would need a way to verify and then do nothing if it fails.


Solution

  • This question isn't exactly the same, but the authorizer concept might be interesting to you:

    How to use Linq to Twitter inside a web service?

    Essentially, you want to instantiate an authorizer, assigning values to the Credentials property, like this:

        var auth = new SingleUserAuthorizer
        {
            Credentials = new SingleUserInMemoryCredentials
            {
                ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
                TwitterAccessToken = ConfigurationManager.AppSettings["twitterAccessToken"],
                TwitterAccessTokenSecret = ConfigurationManager.AppSettings["twitterAccessTokenSecret"]
            }
        };
    

    Then, instantiate your TwitterContext, like this:

        var ctx = new TwitterContext(auth);
    

    The particular authorizer, in this case, is SingleUserAuthorizer but you can use the same authorizer you used to get the original credentials. Just provide all 4 credentials and LINQ to Twitter will bypass the user re-direct for authorization on Twitter.