【问题标题】:I am using csharp to get an access token from Autorization code我正在使用 csharp 从授权码中获取访问令牌
【发布时间】:2018-02-09 03:53:28
【问题描述】:

我正在使用 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

字符串 clientId = "4eae99d7317bf63ba9204accbb76635d528b6a12559464ed1789ef3e5e6ca2f2"; 字符串秘密=“04cecca5a04d31e17cd29979de2da585bfd7ce2e2036c41f276131dfbd2d2ef2”; 字符串 AUTHORIZATION_CODE = "2477b8473fa06b4816fd33e91d782d2e388642539a4e31ce9560b65d28e7fcff"; string redirect_uri = "urn:ietf:wg:oauth:2.0:oob"; string token = GetAccessToken(clientId, secret, AUTHORIZATION_CODE, redirect_uri);

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

任何帮助将不胜感激

【问题讨论】:

    标签: c#


    【解决方案1】:

    试试这个

    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; }
            }
    

    【讨论】:

    • 谢谢。请问如何将它集成到我上面提到的现有代码中?
    • 首先,请告诉我,当你的请求是 GET 时,你为什么使用 POST?我认为如果您将在 GET 上替换 POST 它可能会对您有所帮助。如果不是,我将使用 httpclient 编写代码
    • 如果您查看文档 Accessing token uses POST on their guide developers.universe.com/v2/reference
    • 对不起,现在我看到了。你用你的价值观尝试过演示吗?
    • 我在哪里做呢?
    【解决方案2】:

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

    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 – URL 必须与传递给 /authorize 的 redirect_uri 完全匹配,这意味着您应该首先调用 /authorize。您还应该为这两个请求使用相同的 CookieContainer。 我还建议您将 UserAgent 标头添加到您的请求中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 2015-02-24
      • 2018-09-25
      • 1970-01-01
      • 2020-01-19
      • 2018-06-13
      • 1970-01-01
      相关资源
      最近更新 更多