【发布时间】:2021-08-31 15:55:50
【问题描述】:
我有一个授权码,在调用 api 时我需要在正文中传递一些标头值。当从邮递员那里尝试相同的工作时,它工作正常,但 C# Webclient 抛出 403 错误。
代码如下:-
公共字符串 GetResponse(字符串 AuthCode) {
string url = "https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa";
Uri uri = new Uri(string.Format(url));
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "code=" + AuthCode + "&redirect_uri=" + "http://localhost:8080";
byte[] data = Encoding.GetEncoding("UTF-8").GetBytes(postData);
// Create the request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Basic " + "MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc=");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = data.Length;
httpWebRequest.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36";
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
// Get the response
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception ex)
{
Console.WriteLine("Exception while getting resource " + ex.Message);
return null;
}
string result = null;
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return result;
}
邮递员卷曲命令:-
从 curl 请求生成:
curl -X POST 'https://example.com//openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa' -H '授权:基本 MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc= -H '缓存控制:无缓存' -H '内容类型:应用程序/x-www-form-urlencoded' -d 'code=93317468-7464-4804-b38a-43e13265c4ac&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F'
我无法弄清楚问题所在。谁能帮帮我
【问题讨论】:
-
postData 不是表单数据编码的。注意带有 curl 的帖子正文的区别:
redirect_uri=http%3A%2F%2Flocalhost%3A8080%2F -
尝试编码 Redirect_URl 得到相同的禁止错误:(
-
也许您可以使用 Fiddler 之类的工具来显示两者的完整示例请求?
-
我还注意到重定向 uri 在您的 curl 请求中以
/结尾,但在您的代码中没有。 -
如果重定向 uri 有任何问题,它将给出如下错误:-{ "error_description": "提供的重定向 URI 与预先注册的值不匹配。", "error": " redirect_uri_mismatch" } 我在邮递员中试过
标签: c# curl asp.net-web-api postman