簡體   English   中英

c# 獲取 oauth2 令牌但得到錯誤(遠程服務器返回 400 Bad Request)

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

我正在嘗試使用此 C# 從網站獲取 oauth 令牌。 但以下代碼返回“404 Bad Request”錯誤。 我的代碼有什么問題嗎? 網站工程師說應該返回一個 JSON 文件以顯示錯誤詳細信息。 如何獲取 JSON 文件? 我能看到的只是 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();

我使用 Postman 發送請求,我可以在其響應中獲取令牌。 我應該如何修改我的 C# 代碼來獲取令牌? 在此處輸入圖像描述

你能這樣試試嗎

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM