Search code examples
google-hangoutsgoogle-chat

Create a space with Google Chat REST API


We have a program that uses a service account to manage various thing inside Google Chat.

Now, we have the need to create a new space using the Google Chat REST API (spaces.create). We already joined the developer preview program, as this endpoint is not yet generally available.

From what we understand, this endpoint is not possible to invoke via service account and so we wanted to ask you… can we invoke this endpoint automatically using “domain delegation”? If yes, how?

We always want to use the service account as it is not possible to show a login prompt to the user.

We enabled the domain delegation but that endpoint returns always status 403. (We are using Google.Apis library for .NET Core

using Google.Apis.Auth.OAuth2;

var credential = GoogleCredential.FromFile("key.json")
    .CreateScoped("https://www.googleapis.com/auth/chat.spaces.create")
    .CreateWithUser("[email protected]");

var token = await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();

HttpRequestMessage request = new(HttpMethod.Post, "https://chat.googleapis.com/v1/spaces");
request.Headers.Authorization = new("Bearer", token);

var payload = @"
{
    ""name"": ""testspace-1"",
    ""spaceType"": ""SPACE"",
    ""singleUserBotDm"": true,
    ""displayName"": ""Test Space""
}
";

request.Content = new StringContent(payload, System.Text.Encoding.UTF8, "application/json");

HttpClient client = new();

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();


Solution

  • If you check the documentation Auth

    You will notice it stats that service account authorization is supported. If you are part of thedeveloper preview program

    enter image description here

    The reason I asked about your code is that the last time i tried this which notably was a while ago. The google .net client library was not generated the methods that were under preview.

    So while it may work yes. The issue your may have is that the client library when loaded will not have the method you need meaning you will have to code the call to the endpoint yourself.

    If this is in fact the case let me know if you have any issues peceing it together I may be able to help.

    update your code

    There is an error in your code

     .CreateWithUser("[email protected]");
    

    The email in CreateWithUser should be the user on your domain who you wish to delicate the service account as. Not the service account email address.