[英]How to get auth code and access code in oauth2 api using c#
I am trying to use sage API which uses oauth2 like facebook and google API.我正在尝试使用像 facebook 和 google API 一样使用 oauth2 的 sage API。 I need to get the authorisation code and exchange it for a access token using Asp.Net C#.
我需要获取授权代码并使用 Asp.Net C# 将其交换为访问令牌。 My code to manually retrieve the authorisation code is as follows (I am signing in, authorising it, then manually retrieving it from the URL, is this right?):
我手动检索授权码的代码如下(我是登录,授权,然后从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_");
}
I then manually import the authorisation code into a model and use the following code to post the information to the token URL:然后我手动将授权代码导入模型并使用以下代码将信息发布到令牌 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;
}
}
This should return the access code but throws an error saying "The auth code you transmitted has an unexpected format".这应该返回访问代码,但会引发错误,提示“您传输的身份验证代码具有意外格式”。 My access token model is as follows:
我的访问令牌模型如下:
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; }
}
Does anyone have any ideas how I am doing this wrong, sage does not provide help for developers beyond postman.有没有人知道我是如何做错的,sage 不为邮递员以外的开发人员提供帮助。
You are sending the data to the token endpoint as JSON.您将数据作为 JSON 发送到令牌端点。 You should be sending them as form data (with content type
application/x-www-form-urlencoded
).您应该将它们作为表单数据发送(内容类型为
application/x-www-form-urlencoded
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.