简体   繁体   English

使用C#中的Oauth1从REST API获取请求令牌

[英]Obtain Request Token From REST API using Oauth1 in C#

As the title states, I just need help with the first part of OAuth1.0 authentication: obtaining the request token. 如标题所示,我只需要OAuth1.0身份验证的第一部分的帮助:获取请求令牌。 I am doing this in a console application using C#. 我正在使用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. 当使用未经身份验证的API(例如http://rest-service.guides.spring.io/greeting )时,此方法可以很好地工作,但以这种方式运行时会收到401 Forbidden。 What am I missing? 我想念什么? BTW, I'm brand new to API's. 顺便说一句,我是API的新手。

You must have a key and secret, or username and password. 您必须具有密钥和机密,或用户名和密码。 Both of them are very necessary to fetch access_token. 两者都是获取access_token的必要条件。 i suggest use google postman tool it makes life lot easier in case of api's. 我建议使用Google Postman工具,如果使用api,它会使生活变得更加轻松。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM