Showing posts with label oAuth. Show all posts
Showing posts with label oAuth. Show all posts

Authenticate with oAuth2 and call API using Fiddler

I have a C# MVC web application that uses the OWIN ASP.Net Identity framework in which I've implemented an OAuth 2.0 server.  I'm working on a short proof of concept mobile application where I'd like to authenticate against my web application and call some API's.   I want to keep this as quick and simple as possible for now and manually make the http requests to authenticate and call an API using an access token.

The first step is to make a http request to get back an access token:
POST https://web.app.com/oauth/token HTTP/1.1
User-Agent: Fiddler
content-type: application/x-www-form-urlencoded
Host: web.app.com
Content-Length: 107

client_id=<client id>&client_secret=<client secret>&grant_type=password&username=<username>&password=<password>
The response from that request, if successful, will contain amongst other things and access_token:
{ 
   "access_token":"fwYAnCbseG-Pu-oAMs7nsIbO-v6FmjMHa0VgWQ8YKrmIGcWX5XUQCZ_2OrtZHVUBZVY5ydptAr93YrwxcsBiAdktbJc8P-6cQNPRBhdt3832nKsq5hgJX8fNSsEAPRQcGSb5oyX4EbdhsVgrwdl6aZMVfChmTGCCSgYXK7xkQvAC9heT9k5zkCNPkiE4ob3mE-AL8RILuQFM8bSrSuvgOQByBzyWf-AfMK0EeCOZgfHKur-LqgguQ_ATbCB-rLDG7xWImouJ4ONJ2kmap3X24LECUTUFNhdGtTEtMZtKPZlnhaFVjYvSCQTWNvI_42tUOTz7QEbJDtBgPoG2PrAmtnU1kYJkLPJsZAwSSzue-_Fy9l0rE-RKy5M7z2f_vDedIbMYc186pXDJYZYU7UFR-Seam-itol84Ks0R7dSo990e5QiOcns11Qvqxqrt3GcNKeHE9Fn7zaUgow61LiO7A6Fv9oT17Bv4ShpNve_aLd8qrQg7",
   "token_type":"bearer",
   "expires_in":1199,
   "refresh_token":"7enHr2DzeLvq2v2z-D8G04AfrDn7fmZ25QvFhn100YzlMWJtjvte38wG17KyInKWAxslo_awGKngpVs18bQiUvK2tlD9OhAvxLEU2vpstqdXM2zFRNutOOMx6diD6Y50NecAgPBh18i_dHSv1Fz7xNo0UaMai1UgEwzCUyWNYtLLSLOu9HQkRa3LM90Rgw69LKt8c6JhIqRN6gO_h5SgArWr45XaCdUjU-0OljqLORxOGiRCzn7ckoYRDyqHE5aXKgTr8zGWkBPLlaqOqIEwtCpI3IW55rzEFq5NQiEiOxPhK59ZVxIPQGdmkhwoyjG4VrkocRCRYSUKJqwCixrpWXGEYHfwfItQKz1OwqH112641CSiaLgPInBGQ8OQb9-fYsuqq46J-D9GBb0Tc0fZrJiHkVJjDzxjaDNqct2hCQIr3zqmTuGGwozQFh9BzQGLOoODKpmiZhZJkt2v-JqIOJLHqIFdxpgGJPI6hEpM41W0VqNx",  
   ".issued":"Thu, 11 Feb 2016 10:07:03 GMT",
   ".expires":"Thu, 11 Feb 2016 10:27:03 GMT",
   "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name":"username",
   "urn:oauth:scope":""
}
Now we have authenticated we can use the access token to make a http request to an API endpoint:
GET https://web.app.com/api/v1/route HTTP/1.1
User-Agent: Fiddler
content-type: application/x-www-form-urlencoded
Host: web.app.com
Content-Length: 0
Authorization: Bearer sSijb61BQZMXLNelOUpf-vpBcP49kXarZ2HeA_zTrkiJ_ouGxypzlYjsnL6rA5Igs-WlHblc6L5Czylgo-_UYfkm0kYxqQKKY0O--HQew8QpskaJrvhzvsN56UHDQ25R2Q0Aorn08ae80nq1Hvrrah7JG1xpq4knUYGime_VXp6K4kqCWiI3qjcAD-ONaFlZPKa3l_qpFVgd2alv-0R9MZ4kJ3UIy3jRYpPaUSfkVkEhRMUtIQQNup7XctYNwavlLBAWEQnd2NK8OTaHkf4FBANPOiJlwc2r8rYTOpBPptlLdPLecwTP50Ll49xwoHbfSyBgJ3UnQMxAiejpTzpIP63CGuon0t75ZhVlf2665n892NXQqaplNQ2TrfNbHOM7gI2-qx7kd2DNUYXBXIQWrOW5NX8-nGuhH9YVqawdL_yEeZ9WbDEgAqED7c4BBvmMitcI4LgCLyaISvJ6D4O1Zxr5rTPAXGXsYbdZZdcFguAmvc7m
In the GET request we need to add an Authorization header with a value of "Bearer " plus the access token. I've written this post as a reminder to myself on how to follow the oAuth flow using Fiddler, there are lots of examples out there on S*#toverflow most of which are rubbish.

Tweet from Powershell using oAuth

I wanted to be able to post tweets from a Powershell script. There are alot of old blog posts and examples of composing tweets before Twitter introduced oAuth. I've seen a few examples of Powershell scripts that can post tweets using external dll's to handle the oAuth authentication. I wanted to keep my script self contained and only use .NET Framework assemblies where necessary and not rely on 3rd party dlls.

The first step is to create a Twitter application by logging on to http://dev.twitter.com. Complete the Application Details making sure to set the Application Type - Access to at least Read and Write. Make a note of the following:

  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret

You'll need to update the associated Powershell script variables with your real values.

[Reflection.Assembly]::LoadWithPartialName("System.Security")
[Reflection.Assembly]::LoadWithPartialName("System.Net")

$status = [System.Uri]::EscapeDataString("My first tweet from Powershell");
$oauth_consumer_key = "<consumer key>";
$oauth_consumer_secret = "<consumer secret>";
$oauth_token = "<auth token>";
$oauth_token_secret = "<auth token secret>";
$oauth_nonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()));
$ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime();
$oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();

$signature = "POST&";
$signature += [System.Uri]::EscapeDataString("http://api.twitter.com/1/statuses/update.json") + "&";
$signature += [System.Uri]::EscapeDataString("oauth_consumer_key=" + $oauth_consumer_key + "&");
$signature += [System.Uri]::EscapeDataString("oauth_nonce=" + $oauth_nonce + "&"); 
$signature += [System.Uri]::EscapeDataString("oauth_signature_method=HMAC-SHA1&");
$signature += [System.Uri]::EscapeDataString("oauth_timestamp=" + $oauth_timestamp + "&");
$signature += [System.Uri]::EscapeDataString("oauth_token=" + $oauth_token + "&");
$signature += [System.Uri]::EscapeDataString("oauth_version=1.0&");
$signature += [System.Uri]::EscapeDataString("status=" + $status);

$signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + "&" + [System.Uri]::EscapeDataString($oauth_token_secret);

$hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
$hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key);
$oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)));

$oauth_authorization = 'OAuth ';
$oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",';
$oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",';
$oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",';
$oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'
$oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'
$oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",';
$oauth_authorization += 'oauth_version="1.0"';

$post_body = [System.Text.Encoding]::ASCII.GetBytes("status=" + $status); 
[System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create("http://api.twitter.com/1/statuses/update.json");
$request.Method = "POST";
$request.Headers.Add("Authorization", $oauth_authorization);
$request.ContentType = "application/x-www-form-urlencoded";
$body = $request.GetRequestStream();
$body.write($post_body, 0, $post_body.length);
$body.flush();
$body.close();
$response = $request.GetResponse();