Click here to Skip to main content
13,260,383 members (43,939 online)
Click here to Skip to main content
Add your own
alternative version


52 bookmarked
Posted 29 Aug 2011

Twitter OAuth authentication using .NET

, 26 Aug 2014
Rate this:
Please Sign up or sign in to vote.
A example showing how to authenticate a Twitter application using oAuth and the application access token.


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 plug-ins 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.


The 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 Code

The 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";

We also need to define some details about the request. This includes a unique oauth_nonce parameter which must be generated per request, and a timestamp.

var oauth_version          = "1.0";
var oauth_signature_method = "HMAC-SHA1";
var oauth_nonce            = Convert.ToBase64String(
                                  new ASCIIEncoding().GetBytes(
var timeSpan               = DateTime.UtcNow
                                  - new DateTime(1970, 1, 1, 0, 0, 0, 0,
var oauth_timestamp        = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
var resource_url           = "";
var status                 = "Updating status via REST API if this works";

The next step is to generate an encrypted oAuth signature which Twitter will use to validate the request. To do this, all of the request data is concatenated into a particular format as follows.

var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +

var baseString = string.Format(baseFormat,

baseString = string.Concat("POST&", Uri.EscapeDataString(resource_url), 
             "&", Uri.EscapeDataString(baseString));

Using this base string, we then encrypt the data using a composite of the secret keys and the HMAC-SHA1 algorithm.

var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
                        "&",  Uri.EscapeDataString(oauth_token_secret));

string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
    oauth_signature = Convert.ToBase64String(

The oAuth signature is then used to generate the Authentication header. This requires concatenating the public keys and the token generated above into the following format.

var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
                   "oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
                   "oauth_token=\"{4}\", oauth_signature=\"{5}\", " +

var authHeader = string.Format(headerFormat,

We are now ready to send the request, which is the easy part. Note, we must also disable the Expect: 100-Continue header using the ServicePointManager. Without this code, .NET sends the header by default, which is not supported by Twitter.

var postBody = "status=" + Uri.EscapeDataString(status);

ServicePointManager.Expect100Continue = false;

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream stream = request.GetRequestStream())
    byte[] content = ASCIIEncoding.ASCII.GetBytes(postBody);
    stream.Write(content, 0, content.Length);
WebResponse response = request.GetResponse();


This example hopefully shows how OAuth can be implemented with fairly little effort. In the example provided, I've kept everything inline for clarity; however, in the real world, you would obviously refactor the code into more sensible layers.

In this way, it's possible to build some highly testable lightweight classes in order to generate the required message signature, make the requests, and handle the response.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

United Kingdom United Kingdom
Mike Carlisle - Technical Architect with over 20 years experience in a wide range of technologies.


You may also be interested in...


Comments and Discussions

AnswerRe: The remote server returned an error: (401) Unauthorized. Pin
Pratik Thakker1-Apr-14 4:41
memberPratik Thakker1-Apr-14 4:41 
Questioncan we use same code for searching twitter statuses? Pin
webdev828-Nov-13 16:34
memberwebdev828-Nov-13 16:34 
QuestionGreat but Working only for one time Pin
Robot With Defects2-Oct-13 9:14
memberRobot With Defects2-Oct-13 9:14 
AnswerRe: Great but Working only for one time Pin
TheCodeKing16-Oct-13 4:29
memberTheCodeKing16-Oct-13 4:29 
Questionupdated version for api 1.1 Pin
THESIS_NAIM15-Jul-13 5:11
memberTHESIS_NAIM15-Jul-13 5:11 
QuestionThe remote server returned an error: (410) Gone. Pin
Biswanath Banik2-Jul-13 2:35
memberBiswanath Banik2-Jul-13 2:35 
AnswerRe: The remote server returned an error: (410) Gone. Pin
TheCodeKing16-Oct-13 4:28
memberTheCodeKing16-Oct-13 4:28 
Question401 error Pin
Liza Kelly18-Jun-13 0:33
memberLiza Kelly18-Jun-13 0:33 
Member 297027013-Jun-13 14:12
memberMember 297027013-Jun-13 14:12 
femi214-Jun-13 2:51
memberfemi214-Jun-13 2:51 
Liza Kelly14-Jun-13 3:52
memberLiza Kelly14-Jun-13 3:52 
Member 297027014-Jun-13 12:35
memberMember 297027014-Jun-13 12:35 
Liza Kelly18-Jun-13 0:32
memberLiza Kelly18-Jun-13 0:32 
Liza Kelly18-Jun-13 6:02
memberLiza Kelly18-Jun-13 6:02 
Member 297027018-Jun-13 8:42
memberMember 297027018-Jun-13 8:42 
QuestionGetting 401 after modifying for Stream API Pin
femi213-Jun-13 3:12
memberfemi213-Jun-13 3:12 
AnswerRe: Getting 401 after modifying for Stream API Pin
Member 297027014-Jun-13 12:55
memberMember 297027014-Jun-13 12:55 
AnswerRe: Getting 401 after modifying for Stream API Pin
saravanan R16-Oct-13 1:55
membersaravanan R16-Oct-13 1:55 
QuestionFor Search Pin
Senthil Nathan15-Apr-13 14:59
memberSenthil Nathan15-Apr-13 14:59 
GeneralMy vote of 5 Pin
cellurl28-Mar-13 9:08
membercellurl28-Mar-13 9:08 
QuestionUsing Get method Pin
bobbykc12-Mar-13 6:59
memberbobbykc12-Mar-13 6:59 
AnswerRe: Using Get method Pin
bobbykc13-Mar-13 7:45
memberbobbykc13-Mar-13 7:45 
GeneralRe: Using Get method Pin
Roger Hamilton21-Mar-13 16:34
memberRoger Hamilton21-Mar-13 16:34 
GeneralRe: Using Get method Pin
saravanan R16-Oct-13 1:20
membersaravanan R16-Oct-13 1:20 
AnswerRe: Using Get method Pin
Treckstar14-Jun-13 6:51
memberTreckstar14-Jun-13 6:51 
GeneralGreat Article! Pin
girishraja11-Mar-13 14:10
membergirishraja11-Mar-13 14:10 
QuestionWorks perfectly with "POST" but when I try "GET" it keeps telling me 'UnAuthorized' "Twitter api 1.1" Pin
starrysky886-Nov-12 20:53
memberstarrysky886-Nov-12 20:53 
AnswerRe: Works perfectly with "POST" but when I try "GET" it keeps telling me 'UnAuthorized' "Twitter api 1.1" Pin
Travelthrprog4-Jan-13 10:56
memberTravelthrprog4-Jan-13 10:56 
AnswerRe: Works perfectly with "POST" but when I try "GET" it keeps telling me 'UnAuthorized' "Twitter api 1.1" Pin
bobbykc13-Mar-13 7:46
memberbobbykc13-Mar-13 7:46 
Questionerror : remote server returned an error: (401) Unauthorized. Pin
irafN7865-Nov-12 15:39
memberirafN7865-Nov-12 15:39 
AnswerRe: error : remote server returned an error: (401) Unauthorized. Pin
TheCodeKing5-Nov-12 21:09
memberTheCodeKing5-Nov-12 21:09 
QuestionWork only for status updates???? Pin
Adrien Cdp Martin30-Oct-12 4:48
memberAdrien Cdp Martin30-Oct-12 4:48 
QuestionWorks perfectly Pin
WhiteSites28-Oct-12 15:28
memberWhiteSites28-Oct-12 15:28 
QuestionAPI 1.1 authentication with a GET request Pin
gwilhelmunc18-Oct-12 11:37
membergwilhelmunc18-Oct-12 11:37 
QuestionGraceful 401 (Unauthorized) response handling Pin
rhamstak6-Oct-12 14:35
memberrhamstak6-Oct-12 14:35 
Question401 Unathorized Pin
AGILanham5-Oct-12 11:47
memberAGILanham5-Oct-12 11:47 
AnswerRe: 401 Unathorized Pin
BigBlownDog6-Oct-12 12:17
memberBigBlownDog6-Oct-12 12:17 
AnswerRe: 401 Unathorized Pin
pstarkov7-Oct-12 23:16
memberpstarkov7-Oct-12 23:16 
Questionproblem with Twitter OAuth authentication using .NET Pin
gauravkmspn20-Sep-12 4:21
membergauravkmspn20-Sep-12 4:21 
AnswerRe: problem with Twitter OAuth authentication using .NET Pin
TheCodeKing20-Sep-12 10:49
memberTheCodeKing20-Sep-12 10:49 
QuestionHow to generate OAuth signature with c# for Twitter API 1.1? Pin
smraj150319-Sep-12 19:05
membersmraj150319-Sep-12 19:05 
AnswerRe: How to generate OAuth signature with c# for Twitter API 1.1? Pin
TheCodeKing4-Oct-12 13:29
memberTheCodeKing4-Oct-12 13:29 
QuestionThank you Pin
Ankur Dalal12-Jul-12 23:03
memberAnkur Dalal12-Jul-12 23:03 
QuestionCoding Pin
LamboLambo29-May-12 0:17
memberLamboLambo29-May-12 0:17 
GeneralUsing this program from Localhost!! Pin
simplybj25-Apr-12 20:47
membersimplybj25-Apr-12 20:47 
GeneralRe: Using this program from Localhost!! Pin
Member 432746130-Apr-12 23:00
memberMember 432746130-Apr-12 23:00 
GeneralRe: Using this program from Localhost!! Pin
WillShakespeare16-May-12 1:53
memberWillShakespeare16-May-12 1:53 
QuestionUsing VB.NET instead of C# Pin
WillShakespeare20-Feb-12 23:43
memberWillShakespeare20-Feb-12 23:43 
AnswerRe: Using VB.NET instead of C# Pin
WillShakespeare21-Feb-12 1:44
memberWillShakespeare21-Feb-12 1:44 
GeneralRe: Using VB.NET instead of C# Pin
TheCodeKing22-Feb-12 21:27
memberTheCodeKing22-Feb-12 21:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171114.1 | Last Updated 26 Aug 2014
Article Copyright 2011 by TheCodeKing
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid