c#中的OAuth获取访问令牌

时间:2018-08-31 16:44:39

标签: c# asp.net

我想通过在示例沙箱URL中发送客户端ID和密钥来获取访问令牌。有人可以在C#中提供示例代码来帮助我吗?

import requests
from requests.auth import HTTPBasicAuth

consumer_key = "utuhfhnxjdjd"
consumer_secret = "99ehdjncnv"
api_URL = "https://example.com/oauth/v1/generate?grant_type=client_credentials"

r = requests.get(api_URL, auth=HTTPBasicAuth(consumer_key, consumer_secret))

print (r.text)

1 个答案:

答案 0 :(得分:0)

下面是一个示例,该示例如何设置包装HTTPClient的类,以便使用基本身份验证来调用REST WebService:

https://gist.github.com/snafu918/b064624a4d5cd78533e0479680bb35ce

    public class XyzServiceClient
    {
        internal static HttpClient Client { get; set; } = new HttpClient();
        private readonly string _uri;


        public XyzServiceClient(string apiUrl)
        {
            _uri = apiUrl;
            Client.DefaultRequestHeaders.Clear();
        }

        public Xyz CallService(string username, string password)
        {
            var result = new Xyz();
            HttpResponseMessage response = CallXyzService(username, password);
            return ParseResponse(response, result);
        }

        internal HttpResponseMessage CallXyzService(string username, string password)
        {
            return Client.SendAsync(CreateHttpRequestMessage(username, password)).Result;
        }

        internal HttpRequestMessage CreateHttpRequestMessage(string username, string password)
        {
            var msg = new HttpRequestMessage(HttpMethod.Get, _uri);
            var authByteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
            msg.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authByteArray));
            return msg;
        }

        internal Xyz ParseResponse(HttpResponseMessage response, Xyz result)
        {
            if (response == null || !response.IsSuccessStatusCode)
            {
                throw new Exception("Response from service indicates failure.");
            }

            using (HttpContent content = response.Content)
            {
                string contentResult = content.ReadAsStringAsync().Result;
                // do something to create your Xyz object using data in 
                //contentResult

             }
             return xyzResult;
            }
        }