The remote server returned an error: (400) Bad Request

Hello all,

My OAuth app works fine with postman but I get “The remote server returned an error: (400) Bad Request” error with visual studio c# code.

        public async Task<string> GetAccessTokenResponseTextAsync()
        {

            string BaseUrl = "https://api.zoom.us/v2";
            string OAuthURI = "https://zoom.us/oauth/authorize";
            string TokenUrl = "https://zoom.us/oauth/token";
            string ClientId = "ClientId ";
            string ClientSecret = "ClientSecret ";


            string authorizationResponseText;
            HttpWebRequest authorizationRequest = (HttpWebRequest)WebRequest.Create(new Uri(TokenUrl));
            authorizationRequest.Accept = "application/json";
            authorizationRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            authorizationRequest.Method = "POST";
            string authorizationRequestBody = "response_type=code&client_id=" + HttpUtility.UrlEncode(ClientId) + "&redirect_uri=" + HttpUtility.UrlEncode("https://oauth.pstmn.io/v1/callback");
            UTF8Encoding textEncoderWithoutBOM = new UTF8Encoding(false);
            byte[] authorizationRequestBodyBytes = textEncoderWithoutBOM.GetBytes(authorizationRequestBody);
            authorizationRequest.ContentLength = authorizationRequestBodyBytes.Length;
            using (Stream authorizationRequestStream = await authorizationRequest.GetRequestStreamAsync().ConfigureAwait(false))
            {
                await authorizationRequestStream.WriteAsync(authorizationRequestBodyBytes, 0, authorizationRequestBodyBytes.Length).ConfigureAwait(false);
                authorizationRequestStream.Close();
                WebResponse authorizationResponse;
                try
                {
                    authorizationResponse = await authorizationRequest.GetResponseAsync().ConfigureAwait(false);
                }
                catch (WebException problem)
                {
                    authorizationResponse = problem.Response;
                    throw;
                }

                using (authorizationResponse)
                {
                    authorizationResponseText = await ServerToServer.ReadResponseTextForResponseAsync(authorizationResponse).ConfigureAwait(false);
                    authorizationResponse.Close();
                }
            }

            return authorizationResponseText;
        }

Any help please.
Thank you

@khedr.developer ,

This code is for C# .net 6.0 and you should find this helpful. You will however need to change the redirectURL to your own hosted service

Just to confirm, you are doing OAuth and not Server to Server OAuth right?
The code sample below is for OAuth flow only.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
public static class redirectforoauth
{
 
    public static Task RedirectForOauth(HttpContext context)
    {
        return Task.Run(async () =>
        {

          
            String AppClientID = Environment.GetEnvironmentVariable("OAUTH_CLIENT_ID"); ;
            String AppClientSecret = Environment.GetEnvironmentVariable("OAUTH_CLIENT_SECRET"); ;
            String redirectURL = "https://csharp.asdc.cc/redirectforoauth";

            var authorizationToken = context.Request.Query["code"].ToString();

            try
            {
                using (HttpClient _httpClient = new HttpClient())
                {
                    var url = "https://zoom.us/oauth/token";

                    using var client = new HttpClient();

                    // Encode the client ID and client secret
                    var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{AppClientID}:{AppClientSecret}"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);


                    var content = new FormUrlEncodedContent(new Dictionary
                {
                    { "grant_type", "authorization_code" },
                    { "redirect_uri", redirectURL },
                    { "code", authorizationToken }
                });

                    var response = await client.PostAsync(url, content);


                    if (response.IsSuccessStatusCode)
                    {
                        var responseContent = await response.Content.ReadAsStringAsync();
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(responseContent));

                    }
                    else
                    {
                        // Handle error response
                        await context.Response.WriteAsync(JsonConvert.SerializeObject(response.StatusCode));

                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // Handle HTTP request exceptions
                Console.WriteLine($"HTTP Request Exception: {ex.Message}");
                //throw new Exception($"HTTP Request Exception: {ex.Message}");
            }
            catch (System.Text.Json.JsonException ex)
            {
                // Handle JSON parsing exceptions
                Console.WriteLine($"JSON Parsing Exception: {ex.Message}");
                throw new Exception($"JSON Parsing Exception: {ex.Message}");
            }
            catch (Exception ex)
            {
                // Handle other exceptions
                Console.WriteLine($"Exception occurred: {ex.Message}");
                throw new Exception($"Exception occurred: {ex.Message}");
            }
        });
    }

    internal static RequestDelegate RedirectForOauth(string? oAUTH_CLIENT_ID, string? oAUTH_CLIENT_SECRET)
    {
        throw new NotImplementedException();
    }
}





1 Like

@chunsiong.zoom

Thank you for quick response, you right I think the error reason is handling the redirect url by the wpf application. Any ideas how handle redirect url via wpf application?

@khedr.developer

Wpf == client side app. We need your app to be hosted/server side for this oauth flow to work

There are some device based oauth, but they are for mobile devices

1 Like

hi @chunsiong.zoom

Thank you for respond but after change the url to “https://localhost:44359/Callback
still get bad request.

I post wrong data like clientid I get the clientId error message.

Thank you

@elisa.zoom

@khedr.developer localhost is not a publicly accessible URL, hence the redirect will definitely fail.

You will need to use something like ngrok for tunneling or publish your app on a hosted environment where the domain name points to the project.

1 Like

@chunsiong.zoom

Thank you
I did use ngrok and it working like a charm

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.