Making a POST request to an oAuth2 secured API using RestSharp

Recently, a coworker asked me how to best consume (using C#) an oAuth2 secured API which I had deployed.  I have been using RestSharp (along with JSON.NET) to make web requests in some of my applications recently, so I wrote a quick sample application for him demonstrating how to communicate with my API using those libraries.  I included it with the documentation for that API, but I want to share the basic concepts here as well.  Since the API is using oAuth2, the first step is to get an access token using an API key and password:

var url = "https://my.api.endpoint/GetToken";
var apiKey = "api_key";
var apiPassword = "api_password";

//create RestSharp client and POST request object
var client = new RestClient(url);
var request = new RestRequest(Method.POST);

//add GetToken() API method parameters
request.Parameters.Clear();
request.AddParameter("grant_type", "password");
request.AddParameter("username", apiKey);
request.AddParameter("password", apiPassword);

//make the API request and get the response
IRestResponse response = client.Execute<AccessToken>(request);

//return an AccessToken
return JsonConvert.DeserializeObject<AccessToken>(response.Content);

If you were successfully able to authenticate using your API credentials, you should receive a response that contains an access token and other information. Depending on the API you’re accessing, it may look similar to this:

{
  "access_token": "v5s5UckbViR9gZUXiu...",
  "token_type": "bearer",
  "expires_in": 43199,
  "userName": "api_key",
  ".issued": "Sun, 30 Jul 2017 17:05:37 GMT",
  ".expires": "Mon, 31 Jul 2017 05:05:37 GMT"
}

Now that the application has been authenticated and has be granted an access token, we can then provide this token when calling various API methods to get authorization.  Here is a sample POST request to my API, calling the DoStuff() method and including an object which contains the input parameters:

var url = "https://my.api.endpoint/DoStuff";

//create RestSharp client and POST request object
var client = new RestClient(url);
var request = new RestRequest(Method.POST);

//request headers
request.RequestFormat = DataFormat.Json;
request.AddHeader("Content-Type", "application/json");

//object containing input parameter data for DoStuff() API method
var apiInput = new { name = "Matt", age= 34 };

//add parameters and token to request
request.Parameters.Clear();
request.AddParameter("application/json", JsonConvert.SerializeObject(apiInput), ParameterType.RequestBody);
request.AddParameter("Authorization", "Bearer " + access_token, ParameterType.HttpHeader);

//make the API request and get a response
IRestResponse response = client.Execute<ApiResponse>(request);

//ApiResponse is a class to model the data we want from the API response
ApiResponse apiResponse = new ApiResponse(JsonConvert.DeserializeObject<ApiResponse>(response.Content));

And that’s pretty much it – the ApiResponse object now has all the data we need from the server response, whatever that may be depending on the API.  As you can see, both of these libraries together make sending and receiving data to/from a server very easy with just a few lines of code.  Getting authenticated with the API server, sending some data, and receiving a deserialized response is very simple.  More information about RestSharp and JSON.NET can be found here:

http://restsharp.org/

http://www.newtonsoft.com/json

 

Advertisements

Linking to another page using target=”_blank” can hinder performance and pose a security risk

I recently learned that using target="_blank" to have links open in a new tab causes the new page to run on the same process as your page. If the new link is executing large chunks of JavaScript, your page’s performance may also suffer.  But in addition to a potential performance hit, using  target="_blank" is also a security vulnerability.  Using rel=noopener is recommended.  This will prevent the newly opened page from accessing your window object via window.opener.

<a href="http://mylink.com" target="_blank" rel="noopener">My Link</a>

WordPress began implementing this when adding a hyperlink to text and selecting the “Open link in new window/tab” checkbox.  It does not appear that rel=noopener is supported by Edge at this time.

Here is some more info on rel=noopener:

developers.google.com/web/tools/lighthouse/audits/noopener

Here are a few examples demonstrating the security vulnerability and how the page that is linked to can manipulate the original page.

mathiasbynens.github.io/rel-noopener

jakearchibald.com/2016/performance-benefits-of-rel-noopener

You Might Not Need jQuery

Here’s a cool website I found that shows how to do some common tasks using both jQuery and plain vanilla JavaScript:

youmightnotneedjquery.com

I thought it was kinda cool to see what exactly some of the common jQuery functions are actually doing behind the scenes with JS and CSS.  Sometimes I like to keep things as simple as possible, especially for smaller adhoc apps.  Once upon a time I had a small app that needed to make just one single POST request.  Instead of including jQuery as a dependency in the project and written something like this:

$.ajax({
 type: 'POST',
 url: '/my/app/url',
 data: myData
});

I used some plain JS instead like this:

var request = new XMLHttpRequest();
request.open('POST', '/my/app/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(myData);

Check out the GitHub repo as well for lots more examples.

SSL Certificate Explained

I really like this quick and easy to understand explanation of HTTPS/SSL.  I shared this with my company’s blog a few days ago as we are beginning to enforce HTTPS on our applications.  I wanted everyone on my team to understand what HTTPS is, and why it is important that we begin using HTTPS on all the custom apps we develop for clients.