As the title states, I just need help with the first part of OAuth1.0 authentication: obtaining the request token. I am doing this in a console application using C#. I have been working on this for 3 days now and I have tried numerous samples from the internet, but so far nothing works. Here is my current attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
namespace MCAPIClient
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
var values = new Dictionary<string, string>
{
{ "oauth_consumer_key", "<my consumer key>" },
{ "oauth_consumer_secret", "<my secret key>" }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://app.masteryconnect.com/oauth/request_token", content);
var responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine(response.Headers);
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
}
This works beautifully when consuming an API without authentication (like http://rest-service.guides.spring.io/greeting), but receives 401 Forbidden when running it like this. What am I missing? BTW, I'm brand new to API's.
You must have a key and secret, or username and password. Both of them are very necessary to fetch access_token.
i suggest use google postman tool it makes life lot easier in case of api's.
Below code will solve your problem.
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("key:Secret"));
req.Credentials = new NetworkCredential("username", "password");
var postData = "grant_type=client_credentials";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = req.GetResponse();
// Console.WriteLine(((HttpWebResponse)response).StatusDescription);
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Newtonsoft.Json.Linq.JObject o = Newtonsoft.Json.Linq.JObject.Parse(responseFromServer);
String status = (string)o.SelectToken(".access_token");
Related
I'm trying to exchange an authorisation code for an access token using C# on HRMRC Making Tax Digital API. I'm able to get the authorisation code alright which I thought would be the difficult bit.
I've also been able to use Postman to exchange the authorisation code my app has obtained for the access token. See the attached screen shots of Postman and below is my C# :
uri = "https://api.service.hmrc.gov.uk/oauth/token"
body = "client_id=MyClientId&client_secret=MyClientSecret&code=MyAuthorisationCode&grant_type=authorization_code&redirect_uri=http%253A%252F%252Flocalhost%253A80%252F"
private static AccessTokens GetTokens(string uri, string body)
{
AccessTokens tokens = null;
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Accept = "application/vnd.hmrc.1.0+json";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = body.Length;
using (Stream requestStream = request.GetRequestStream())
{
StreamWriter writer = new StreamWriter(requestStream);
writer.Write(body);
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
string json = reader.ReadToEnd();
reader.Close();
tokens = JsonConvert.DeserializeObj[1]ect(json, typeof(AccessTokens)) as AccessTokens;
}
return tokens;
}
I have the access token. How can I make a request using the token in c#?
Here is what I have tried unsuccessfully resulting in error 400 Bad Request.
Note: the url was copied from the YQL console
public static void Request(string token)
{
var request =
WebRequest.Create(
#"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20fantasysports.leagues%20where%20league_key%3D'371.l.4019'&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys");
request.Headers["Authorization"] = $"Bearer {token}";
request.Method = "GET";
request.ContentType = "application/xml;charset=UTF-8";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream == null) return;
var reader = new StreamReader(stream, Encoding.UTF8);
var responseString = reader.ReadToEnd();
}
}
}
http://ssw.com/profile/?apikey = skdwkdkfkkdj
I tried to use
public async Task<string> GetFromUriAsync(string requestUri, string token)
{
var client = new HttpClient();
client.BaseAddress = new Uri(BaseUri);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("apikey", "=" + token);
HttpResponseMessage response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
Then it returns null
Am I missing something or is it just totally wrong?
Thanks
You're trying to pass the API key in the header information of your HTTP request. What you need to do is just pass that whole URL without any additional header information.
IE: use "http://ssw.com/profile?apikey=abcdef" as the requestUri and send token as null. Also, remove the setting of the client.DefaultRequestHeaders.Authorization property. Authorization was meant to be a user/pass system and not a token-based system.
To test this, download Fiddler 4 (https://www.telerik.com/download/fiddler). Once you have fiddler installed, on the "Composer" tab, you can test different queries you need by putting the URL directly into the URL box and clicking "Execute". You'll then be able to use the inspectors to see the responses and figure out where you need to go from there.
Here are the classes I use for HTTP GET and POST operations:
public static string HTTPGET(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
request.Timeout = 100000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
using (StreamReader resStream = new StreamReader(responseStream))
return resStream.ReadToEnd();
return null;
}
catch (Exception e)
{
Console.WriteLine(url);
Console.WriteLine(e);
return null;
}
}
public static string HTTPPOST(string url, string postData)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = "x-www-form-urlencoded";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
using (Stream requestStream = webRequest.GetRequestStream())
requestStream.Write(byteArray, 0, byteArray.Length);
using (Stream responseStream = webRequest.GetResponse().GetResponseStream())
if (responseStream != null)
using (StreamReader responseReader = new StreamReader(responseStream))
return responseReader.ReadToEnd();
return null;
}
catch (Exception e)
{
Console.WriteLine(url);
Console.WriteLine(postData);
Console.WriteLine(e);
return null;
}
}
I use the code below to call an OData service (which is the working service from Odata.org) from C# and I don't get any result.The error is in the response.GetResponseStream().
Here is the error :
Length = 'stream.Length' threw an exception of type 'System.NotSupportedException'
I want to call to the service and parse the data from it, what is the simpliest way to do that?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using System.Xml;
namespace ConsoleApplication1
{
public class Class1
{
static void Main(string[] args)
{
Class1.CreateObject();
}
private const string URL = "http://services.odata.org/OData/OData.svc/Products?$format=atom";
private static void CreateObject()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
XmlTextReader reader = new XmlTextReader(stream);
}
}
}
}
}
I ran your code on my machine, and it executed fine, I was able to traverse all XML elements retrieved by the XmlTextReader.
var request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/xml";
request.Accept = "application/xml";
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
var reader = new XmlTextReader(stream);
while (reader.Read())
{
Console.WriteLine(reader.Value);
}
}
}
But as #qujck suggested, take a look at HttpClient. It's much easier to use.
If you're running .NET 4.5 then take a look at HttpClient (MSDN)
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(endpoint);
Stream stream = await response
.Content.ReadAsStreamAsync().ConfigureAwait(false);
response.EnsureSuccessStatusCode();
See here and here for complete examples
I want to execute a QueryString using WebClient but using the POST Method
That is what I got so far
CODE:
using (var client = new WebClient())
{
client.QueryString.Add("somedata", "value");
client.DownloadString("uri");
}
It is working but unfortunately it is using GET not POST and the reason I want it to use POST is that I am doing a web scraping and this is how the request is made as I see in WireShark. [IT USES POST AS A METHOD BUT NO POST DATA ONLY THE QUERY STRING.]
In answer to your specific question:
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
byte[] response = client.UploadData("your url", "POST", new byte[] { });
//get the response as a string and do something with it...
string s = System.Text.Encoding.Default.GetString(response);
But using WebClient can be a PITA since it doesn't accept cookies nor allow you to set a timeout.
this will help you, use WebRequest instead of WebClient.
using System;
using System.Net;
using System.Threading;
using System.IO;
using System.Text;
class ThreadTest
{
static void Main()
{
WebRequest req = WebRequest.Create("http://www.yourDomain.com/search");
req.Proxy = null;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
string reqString = "searchtextbox=webclient&searchmode=simple";
byte[] reqData = Encoding.UTF8.GetBytes(reqString);
req.ContentLength = reqData.Length;
using (Stream reqStream = req.GetRequestStream())
reqStream.Write(reqData, 0, reqData.Length);
using (WebResponse res = req.GetResponse())
using (Stream resSteam = res.GetResponseStream())
using (StreamReader sr = new StreamReader(resSteam))
File.WriteAllText("SearchResults.html", sr.ReadToEnd());
System.Diagnostics.Process.Start("SearchResults.html");
}
}