Introduction In this article I want to demonstrate how to implement OAuth authentication in .Net. I've previously written about my dislike of third party SDKs for social media integration and how we should leverage technology based solutions instead. One of the sticking points in doing this tends to be that implementing OAuth based authentication is relatively difficult compared with actually making the requests themselves. There is documentation available, but there seems to be a lack of .NET example code to go with it. In keeping with my thoughts in previous articles I would recommend using open source OAuth based libraries to solve this problem, and again avoid resorting to third party Twitter/Facebook implementations which more strongly couple code to specific APIs. This keeps the solution more reusable and builds on specific technologies to better future proof your application. I've also previously shown how client-side plugins can be used in combination with server-side code to speed development in this area. However sometimes authentication does need to be implemented purely on the server-side. So how difficult is this?It turns out implementing OAuth on the server-side in .Net isn't too difficult, the battle is getting the encoding and authentication signature right. With so few examples it can be a little daunting, so here's an example written in pure .NET using the official Twitter OAuth documentation and a bit of trial and error.
BackgroundThe following example shows how to authenticate against the Twitter APIs using a registered Twitter application. Any interaction with the APIs when authenticated in this manner will behave as if coming from the Twitter account under which the application has been registered. It's therefore useful for sending out status updates or sending out notifications from a specific account. Usually OAuth requires redirecting the user to a login screen to obtain an oAuth token which requires a bit more work. However when authenticating via a Twitter application this step is skipped as your application already has an oAuth token provided (access token). Whether you are using the application oAuth token or a user oAuth token, the following code can be used to authenticate against the twitter APIs.
The CodeThe first step is to visit the Twitter developer section and register a new application. On completion you will be provided with a set of public/private keys which you will need the replace in the example below in order to run. The values I have used directly correspond with the documented example here. Make sure you replace them with your own. var oauth_token = "819797-Jxq8aYUDRmykzVKrgoLhXSq67TEa5ruc4GJC2rWimw";
var oauth_token_secret = "J6zix3FfA9LofH0awS24M3HcBYXO5nI1iYe8EfBA";
var oauth_consumer_key = "GDdmIQH6jhtmLUypg82g";
var oauth_consumer_secret = "MCD8BKwGdgPHvAuvgvz4EQpqDAtx89grbuNMRd7Eh98";
Read more: Codeproject
QR: