我正在使用csharp从Autorization代码中获取访问令牌

时间:2017-08-31 08:52:31

标签: c#

我正在使用universe.com API https://developers.universe.com

当我运行以下代码时,我得到401,未经授权的访问。

 public static string GetAccessToken(string clientId, string secret, string AUTHORIZATION_CODE, string redirect_uri)
        {
            var uri = string.Format("https://www.universe.com/oauth/token?grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", clientId, secret, AUTHORIZATION_CODE, redirect_uri);
            var webRequest = (HttpWebRequest)WebRequest.Create(uri);
            webRequest.Method = "POST";
            webRequest.Accept = "application/json";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            var httpResponse = (HttpWebResponse)webRequest.GetResponse();
            using (var reader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var result = reader.ReadToEnd();

                //var credentials = JsonConvert.DeserializeObject<Credentials>(result);

                //return credentials.accessToken;
                return result.ToString();

            }
        }

以下是我的测试申请详情:

申请ID: 4eae99d7317bf63ba9204accbb76635d528b6a12559464ed1789ef3e5e6ca2f2 秘密: 04cecca5a04d31e17cd29979de2da585bfd7ce2e2036c41f276131dfbd2d2ef2 自动化代码:2477b8473fa06b4816fd33e91d782d2e388642539a4e31ce9560b65d28e7fcff 重定向URI(本地主机):urn:ietf:wg:oauth:2.0:oob

string clientId =&#34; 4eae99d7317bf63ba9204accbb76635d528b6a12559464ed1789ef3e5e6ca2f2&#34 ;;             string secret =&#34; 04cecca5a04d31e17cd29979de2da585bfd7ce2e2036c41f276131dfbd2d2ef2&#34 ;;             string AUTHORIZATION_CODE =&#34; 2477b8473fa06b4816fd33e91d782d2e388642539a4e31ce9560b65d28e7fcff&#34 ;;             string redirect_uri =&#34; urn:ietf:wg:oauth:2.0:oob&#34 ;;            string token = GetAccessToken(clientId,secret,AUTHORIZATION_CODE,redirect_uri);

        Console.WriteLine(token.ToString());
        Console.ReadLine();

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

试试这个

public async Task<string> GetAccessToken(string clientId, string redirectUri,string clientSecret, string authCode, string grantType)
        {

            var testData = new Data(){ClientId = clientId,
                ClientSecret = clientSecret,              
             RedirectUri = redirectUri,
             GrantType = grantType,
             Code = authCode
            };

            var uri = 
                $"https://www.universe.com/oauth/token";
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
                var str = JsonConvert.SerializeObject(testData);
                var dataContent = new StringContent(str);
                var response = await httpClient.PostAsync(uri, dataContent);
                return await response.Content.ReadAsStringAsync();
            }

        }
        public class Data
        {
            [JsonProperty("code")]
            public string Code { get; set; }
            [JsonProperty("grant_type")]
            public string GrantType { get; set; }
            [JsonProperty("client_id")]
            public string ClientId { get; set; }
            [JsonProperty("client_secret")]
            public string ClientSecret { get; set; }
            [JsonProperty("redirect_uri")]
            public string RedirectUri { get; set; }
        }

答案 1 :(得分:0)

我认为您应该在正文中传递请求参数(不要将它们嵌入到网址中)

public static string GetAccessToken(string clientId, string secret, string AUTHORIZATION_CODE, string redirect_uri)
{
  try
  {
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://www.universe.com/oauth/token");
    webRequest.Method = "POST";
    webRequest.Accept = "application/json";
    webRequest.ContentType = "application/x-www-form-urlencoded";
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    byte[] buffer = System.Text.Encoding.UTF8.GetBytes(string.Format("grant_type=authorization_code&client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", clientId, secret, AUTHORIZATION_CODE, redirect_uri));
    webRequest.ContentLength = buffer.Length;
    using (var reqStrm = webRequest.GetRequestStream())
    {
     reqStrm.Write(buffer, 0, buffer.Length);
    }

    using (HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse())
    {
        using (StreamReader reader = new StreamReader(resp.GetResponseStream()))
        {
         return reader.ReadToEnd();
        }
    }

  }
  catch (Exception ex){return ex.Message;}
}

也许您仍会收到错误,因为文档here

redirect_uri:REDIRECT_URI - 网址必须与传递给/ authorize的redirect_uri完全匹配,这意味着您应首先调用/授权。您还应该对两个请求使用相同的CookieContainer。 我还建议您将UserAgent标头添加到您的请求中