【问题标题】:403 Forbidden error using Webrequest in C# but works in postman在 C# 中使用 Webrequest 出现 403 禁止错误,但在邮递员中有效
【发布时间】: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


【解决方案1】:

使用 RestSharp 解决问题并传递正确的标头值

var client = new RestClient("https://example.com/openam/oauth2/access_token?grant_type=authorization_code&realm=/cbpgatqa");
            var request = new RestRequest(Method.POST);

            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddHeader("Cache-Control", "no-cache");
            request.AddHeader("Authorization", "Basic MzE4OGQwYjQtZTRlOC00MTZjLTg5NjAtZDNlYWFhMmNjY2IxOkx3NiVBa0x4NWtPM01rJTJ5RWwxbW1jR0ZYZmhTQmk1NHhIRCpzNiUyVUd5WXN0MCNVbyNMNWQhcVlpZE93djc=");
            request.AddParameter("undefined", "code=" + AuthCode + "&redirect_uri=http%3A%2F%2Flocalhost%3A8080", ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);

            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response.Content)))
            {
                // Deserialization from JSON  
                DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Token));
                Token token = (Token)deserializer.ReadObject(ms);
            return  userinfo=  GetuserInfo(token.id_token);
            }

【讨论】:

    【解决方案2】:

    我也面临同样的问题。删除名为 "Host" 的参数后修复它。我正在使用第三方 rest API。他们可能有一些限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2019-06-22
      • 2019-02-28
      • 2020-12-08
      • 2021-01-13
      • 2018-01-16
      相关资源
      最近更新 更多