【问题标题】:How to get auth code and access code in oauth2 api using c#如何使用 c# 在 oauth2 api 中获取身份验证代码和访问代码
【发布时间】:2021-09-05 01:44:00
【问题描述】:

我正在尝试使用 sage API,它使用 oauth2,例如 facebook 和 google API。我需要获取授权代码并使用 Asp.Net C# 将其交换为访问令牌。我手动检索授权码的代码如下(我是登录,授权,然后手动从URL中检索,是这样吗?):

public ActionResult GetRequest()
        {
            var URL = "https://www.sageone.com/oauth2/auth/central?filter=apiv3.1";
            var urlParameters = "&response_type=code&client_id=_client_id_&redirect_uri=_redirect_uri_&state=d57w5d193";
            return Redirect("https://www.sageone.com/oauth2/auth/central?filter=apiv3.1&response_type=code&client_id=_client_id_&redirect_uri=_redirect_uri_&scope=full_access&state=_state_");
        }

然后我手动将授权代码导入模型并使用以下代码将信息发布到令牌 URL:

public async Task<string> GetAccess()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://oauth.accounting.sage.com/token");
                var contentType = new MediaTypeWithQualityHeaderValue("application/json");
                client.DefaultRequestHeaders.Accept.Add(contentType);

                AccessTokenSend accessTokenSend = new AccessTokenSend()
                {
                    client_id = "_client_id_",
                    client_secret = "_client_secret",
                    code = "_authorisation_code_from_url",
                    grant_type = "authorization_code",
                    redirect_url = "_redirect_url"
                };
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(accessTokenSend);
                var data = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");

                var result = await client.PostAsync("https://oauth.accounting.sage.com/token", data);
                string resultContent = await result.Content.ReadAsStringAsync();

                return resultContent;
            }
        }

这应该会返回访问代码,但会引发错误,提示“您传输的身份验证代码具有意外格式”。我的访问令牌模型如下:

public class AccessTokenSend
    {
        public string client_id { get; set; }
        public string  client_secret { get; set; }
        public string code { get; set; }
        public string grant_type { get; set; }
        public string redirect_url { get; set; }
    }

有没有人知道我做错了什么,sage 不为邮递员以外的开发人员提供帮助。

【问题讨论】:

    标签: c# asp.net api oauth-2.0 oauth


    【解决方案1】:

    您将数据作为 JSON 发送到令牌端点。您应该将它们作为表单数据发送(内容类型为application/x-www-form-urlencoded)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-23
      • 2014-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多