Requesting OAuth Token from Zoom API Shortens the access_token attribute, but does not in Postman

854 Views Asked by At

The access_token is always 632 characters long, and when I test it in Postman it works fine

Postman Code:

using System;
using RestSharp;
namespace HelloWorldApplication {
  class HelloWorld {
    static void Main(string[] args) {
      var client = new RestClient("https://zoom.us/oauth/token?account_id=VfdA06Q9TQe31jH7oRutuQ&grant_type=account_credentials");
      client.Timeout = -1;
      var request = new RestRequest(Method.POST);
      request.AddHeader("Authorization", "Basic ####");
      request.AddHeader("Cookie", "####");
      var body = @"";
      request.AddParameter("text/plain", body,  ParameterType.RequestBody);
      IRestResponse response = client.Execute(request);
      Console.WriteLine(response.Content);
    }
  }
}

I have a limitation that prevents me from using RestSharp. As such, I am using System.Net.Http in my application, but the access_token is always 533 characters long. I get unauthorized response whenever I use that token which is what alerted me that something may be wrong with it.

System.Net.Http Code

using System;
using System.Collections.Generic;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApp_Test_ZoomCreateMeeting
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get current token age
        
             // Get the get credentials


            // Build the request body
            var authRequestBody = new FormUrlEncodedContent(new[]
            {
            new KeyValuePair<string, string>("grant_type", "client_credentials"),
            new KeyValuePair<string, string>("client_id", "####"),
            new KeyValuePair<string, string>("client_secret", "####")
        });

            // Set up the HTTP client
            var authClient = new HttpClient();
            authClient.BaseAddress = new Uri("https://zoom.us/");



            // Send the request and get the response
            HttpResponseMessage authResponse = authClient.PostAsync("oauth/token", authRequestBody).Result;

            string content = authResponse.Content.ReadAsStringAsync().Result;
            long contentLength = authResponse.Content.Headers.ContentLength ?? 0;


            string responseContent = authResponse.Content.ReadAsStringAsync().Result;

            // Parse the JSON response
            JObject jsonResponse = JsonConvert.DeserializeObject<JObject>(responseContent);


            // Create an instance of JsonSerializerSettings and set the ReferenceLoopHandling property to Ignore
            JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
            serializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            // Serialize the jsonResponse object using the JsonSerializerSettings object
            string serializedJsonResponse = JsonConvert.SerializeObject(jsonResponse, serializerSettings);

            // Extract the access_token property (value<t>)
            string currentToken = jsonResponse["access_token"].Value<string>();           


            Console.WriteLine("Current Token: " + currentToken);        
            
        }


    }
}

Any ideas on a solution here?

I tried to request an OAuth token from the Zoom API, and though I received one, the access_token attribute is being cut short

1

There are 1 best solutions below

0
Ty Beresford On

Although this thread is older, with Zoom JWT App Type deprecating soon, it seems that this thread could gain traction in the near future. The following uses Zoom Server-to-Server Auth, but can be adjusted for Zoom OAuth.

To begin, Account ID, Client ID, and Client Secret are needed. This can be found in [Created Apps → Your App → App Credentials].

A valid Zoom Access Token takes the form of:

public class ZoomAccessToken
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string scope { get; set; }

}

It gets a little confusing reading Zoom API [https://developers.zoom.us/docs/internal-apps/s2s-oauth/], but mapping a ZoomAccessToken object via a HTTP request boils down to this:

  1. Account ID
  2. Base64 encoded Client ID and Client Secret
  3. Host

The following code is currently implemented in my Zoom Server-to-Server Auth Application to retrieve a valid Zoom Access Token, for reference:

using System.Text.Json.Serialization;

private void GetAccessToken()
{
    var client = new HttpClient();
    client.BaseAddress = new Uri("https://zoom.us/oauth/token");
    var request = new HttpRequestMessage(HttpMethod.Post, string.Empty);
    request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes($"{config.GetValue<string>("Zoom:clientID")}:{config.GetValue<string>("Zoom:clientSecret")}")));
    request.Content = new FormUrlEncodedContent(new Dictionary<string, string>
    {
        { "grant_type", "account_credentials" },
        { "account_id", "your_account_id" }
     
    });
    request.Headers.Host = "zoom.us";

    var response = client.SendAsync(request).Result;

    if (response.IsSuccessStatusCode)
    {
        var content = response.Content.ReadAsStringAsync().Result;
        var token = JsonSerializer.Deserialize<ZoomAccessToken>(content);
        this.accessToken = token;

    }
    else
    {
        // Handle the error
        Console.WriteLine($"Failed to retrieve access token: {response.ReasonPhrase}");

    }

}

Before using the Zoom Access Token (ex. getting Zoom user information), ensure your Zoom Scopes are correct [Created Apps → Your App → Scopes]

Zoom Access Token Usage:

/*
* SCOPES
* /user:read:admin
* /phone_call_control:read:admin
* /phone:read:admin
*/

public class LockedPageUsers
{
    public int page_count { get; set; }
    public int page_number { get; set; }
    public int page_size { get; set; }
    public int total_records { get; set; }
    public string next_page_token { get; set; }
    public List<ZoomUser> users { get; set; }

}

public class ZoomUser
{
    public string account_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string email { get; set; }
    public string phone_number { get; set; }

}

private List<ZoomUser> GetUsers()
{
    List<ZoomUser>ret = new List<ZoomUser>();
    GetAccessToken();
    string nextPageToken = "";

    while (nextPageToken != null)
    {
        var client = new HttpClient();

        client.BaseAddress = new Uri($"https://api.zoom.us/v2/users/?page_size=300&next_page_token={nextPageToken}");

        var request = new HttpRequestMessage(HttpMethod.Get, string.Empty);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.accessToken.access_token);
        request.Headers.Host = "api.zoom.us";

        var response = client.SendAsync(request).Result;

        if (response.IsSuccessStatusCode)
        {
            var content = response.Content.ReadAsStringAsync().Result;
            // Zoom API uses pagination, [currentPagedUsers] holds the deserialized page
            var currentPagedUsers = System.Text.Json.JsonSerializer.Deserialize<LockedPageUsers>(content);

            foreach (var user in currentPagedUsers.users)
            {
                ret.Add(user);
                     
            }
            // Zoom API uses pagination, [nextPageToken] holds the token for iterating to the next page
            nextPageToken = currentPagedUsers.next_page_token;
            // If [nextPageToken] is null, pagination has reached its limit
            if (String.IsNullOrEmpty(nextPageToken)) nextPageToken = null;

        }
        else break;

    }
    return ret;

}