简体   繁体   English

c# 获取 oauth2 令牌但得到错误(远程服务器返回 400 Bad Request)

[英]c# to get oauth2 token but get error (Remote server returns 400 Bad Request)

I am trying to use this C# to get oauth token from a website.我正在尝试使用此 C# 从网站获取 oauth 令牌。 But the below codes return '404 Bad Request' error.但以下代码返回“404 Bad Request”错误。 Is there anything wrong in my code?我的代码有什么问题吗? The website engineer says there should be a JSON file returned to show error details.网站工程师说应该返回一个 JSON 文件以显示错误详细信息。 How do I get that JSON file?如何获取 JSON 文件? What I can see is just 1 line error message in VS2012.我能看到的只是 VS2012 中的 1 行错误消息。

private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
            webRequest.Method = "POST";
            webRequest.AllowAutoRedirect = true;
           

            //write the data to post request
            String postData = "client_id=abc&client_secret=xxx&grant_type=client_credentials";
            byte[] buffer = Encoding.Default.GetBytes(postData);
            if (buffer != null)
            {
                webRequest.ContentLength = buffer.Length;
                webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string strResponse = reader.ReadToEnd();

I used Postman to send a request and I can get the token in its response.我使用 Postman 发送请求,我可以在其响应中获取令牌。 How should I modify my C# codes to get the token?我应该如何修改我的 C# 代码来获取令牌? 在此处输入图像描述

Can you try like this你能这样试试吗

public (string, string, string, string) GetOAuth(string CliendId, string ClientSecret, string OAuthURl)
{
    using (var httpClient = new HttpClient())
    {
        var creds = $"client_id={CliendId}&client_secret={ClientSecret}&grant_type=client_credentials";

        httpClient.DefaultRequestHeaders.Accept.Clear();
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
        var content = new StringContent(creds, Encoding.UTF8, "application/x-www-form-urlencoded");
        var response = httpClient.PostAsync(OAuthURl, content).Result;
        var jsonContent = response.Content.ReadAsStringAsync().Result;

        var tokenObj = JsonConvert.DeserializeObject<dynamic>(jsonContent);
        
        var access_token = tokenObj?.access_token;
        var token_type = tokenObj?.token_type;
        var expires_in = tokenObj?.expires_in;
        var scope = tokenObj?.scope;

        return (access_token, token_type, expires_in, scope);
    }
}

private void HowTOUse()
{
    string access_token, token_type, expires_in, scope;
    (access_token, token_type, expires_in, scope) = GetOAuth("client_id", "client_secret", "oauthurl");
}
   Try using like the below code hope this code will solve the problem

   private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://xxxx.com/api/oauth/token");
        webRequest.Method = "POST";
        webRequest.AllowAutoRedirect = true;
       

        //write the data to post request
        String postData = 
        "client_id=abc&client_secret=xxx&grant_type=client_credentials";
          //byte[] buffer = Encoding.Default.GetBytes(postData);

         //add these lines

        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(postData);
        
        if (buffer != null)
        {
            webRequest.ContentLength = buffer.Length;
            webRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
        }
     try
     { 
        using (HttpWebResponse response = 
           (HttpWebResponse)webRequest.GetResponse())
            {
               using (Stream dataStream = response.GetResponseStream())
                {
                StreamReader reader = new StreamReader(dataStream);
                    string strResponse = reader.ReadToEnd();

              TokenModel  dt = JsonConvert.DeserializeObject<TokenModel> 
                (strResponse);
                    token = dt.accessToken;
                //Assign json Token values from strResponse to model tok_val
                    tok_val.accessToken = dt.accessToken;
                    tok_val.expires_in = dt.expires_in;
                    tok_val.RefreshToken = dt.RefreshToken;
                    tok_val.tokenType = dt.tokenType;
               }
           }
      }


       catch (WebException wex)
        {

            error = "Request Issue: " + wex.Message;
        }
        catch (Exception ex)
        {
            error = "Issue: " + ex.Message;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Oauth2:远程服务器返回错误:(400)错误的请求 - Oauth2: The remote server returned an error: (400) Bad Request C#FCM:远程服务器返回错误:(400)错误的请求 - C# FCM : The remote server returned an error: (400) Bad Request 远程服务器返回错误:C# 代码中的 (400) 错误请求 - The remote server returned an error: (400) Bad Request in C# Code 远程服务器返回错误:(400)错误的请求C# - The remote server returned an error: (400) Bad Request C# LInkedIn oAuth2请求令牌400错误请求 - LInkedIn oAuth2 request token 400 Bad Request Azure AD OAuth2访问令牌请求错误-400错误的请求 - Azure AD OAuth2 Access Token Request Error - 400 Bad Request Google API Oauth2 刷新令牌错误请求 400 - Google API Oauth2 Refresh token bad request 400 我正在尝试使用 c# 从 Twitter api 获取请求令牌,但收到 400 个错误的请求错误 - I am trying to get request token from Twitter api using c#, but getting 400 bad request error C#WCF“ System.Net.WebException:远程服务器返回错误:(400)错误的请求。” - C# WCF “System.Net.WebException: The remote server returned an error: (400) Bad Request.” (400)错误的请求-&gt;远程服务器返回错误:(400)错误的请求 - (400) Bad Request -> The remote server returned an error: (400) Bad Request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM