正如标题所述,我只需要OAuth1.0身份验证的第一部分帮助:获取请求令牌。我在使用C#的控制台应用程序中执行此操作。我已经为此工作了3天了,我已经尝试过来自互联网的大量样本,但到目前为止还没有任何效果。这是我目前的尝试:
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);
}
}
}
}
这在使用没有身份验证的API(如http://rest-service.guides.spring.io/greeting)时非常有效,但在运行时会收到401 Forbidden。我错过了什么?顺便说一句,我是API的新手。
答案 0 :(得分:0)
您必须拥有密钥和密码,或用户名和密码。它们都是获取access_token非常必要的。 我建议使用谷歌邮差工具,它使api的生活更轻松。 下面的代码将解决您的问题。
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");