0

When setting up an application with TradeKing, you get:

  • A Consumer Key
  • A Consumer Secret
  • A Oauth Token
  • A Oauth Token Secret

For accessing TradeKing's API, that's apparently all you need to build personal applications. However, I can't find a way to build the correct Oauth headers in C#/.NET.

The examples seem fairly simple, like this Node.js sample. The Oauth library for Node.js takes care of generating the appropriate headers. There are similar samples for a few other languages, but they all seem to have libraries to build the proper header from the provided keys and tokens. I can't find a library to do this with C#/.NET.

I'm trying to wrap my head around what's going on in this SO question that builds the headers from scratch, but it's pretty advanced. I'm poking around in the ASP.NET Security repo, because they must be handling this somewhere. But I can't quite find what I'm looking for.

How can I generate an Oauth header from these keys with .NET?

Community
  • 1
  • 1
Shaun
  • 2,012
  • 20
  • 44
  • have you checked this http://deanhume.com/home/blogpost/a-simple-guide-to-using-oauth-with-c-/49 – Yordan Mar 22 '17 at 06:17
  • @Yordan I had stumbled across that when in my web searches, but ignored it because the [code it referenced](http://cropperplugins.codeplex.com/SourceControl/changeset/view/72088#Cropper.Plugins/TwitPic/OAuth.cs) was from 2010 and had a poor rating on Codeplex. But with a couple changes I was able to plug it in to my app. Thanks for the push. – Shaun Mar 22 '17 at 13:09

1 Answers1

0

There is an open source library on CodePlex that has some Oauth management classes set up.

I still need to go through it and take out what isn't necessary, but fortunately it doesn't depend on any other classes from the repo. Once I added it to my project, it was pretty easy to test the connection:

public async Task<IActionResult> MakeRequest()
{
    string result;
    var oauth = new Oauth.Manager();
    // _tradeKing is a configuration object I set up to hold user secrets
    oauth["consumer_key"] = _tradeKing.ConsumerKey;
    oauth["consumer_secret"] = _tradeKing.ConsumerSecret;
    oauth["token"] = _tradeKing.OauthToken;
    oauth["token_secret"] = _tradeKing.OauthTokenSecret;

    var url = "https://api.tradeking.com/v1/accounts.json";
    var authzHeader = oauth.GenerateAuthzHeader(url, "GET");
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    request.Headers["Authorization"] = authzHeader;
    var response = await request.GetResponseAsync();
    using (var reader = new StreamReader(response.GetResponseStream()))
    {
        result = reader.ReadToEnd();
    }

    return Content(result);
}

There are some more instructions on how to use it from this SO post.

Shaun
  • 2,012
  • 20
  • 44