Atelier de programmation: Automatiser la validation de domaine pour Google Workspace

Pourquoi automatiser la validation des domaines ?

Bien que l'API Cloud Channel vous permette de provisionner des droits d'accès Google Workspace à grande échelle, le client doit toujours effectuer les actions suivantes pour activer les services.

  1. Accepter les conditions d'utilisation
  2. Valider la propriété du domaine
  3. Configurer les enregistrements MX

Un client nouvellement créé suivra un processus guidé de définition des exigences lorsqu'il accédera à la console d'administration (sur admin.google.com) pour la première fois.

Si vous disposez d'un accès programmatique aux enregistrements DNS du domaine (par exemple, si vous avez revendu le domaine au client), vous pouvez automatiser les étapes 2 et 3 pour augmenter les taux d'activation, car ces étapes nécessitent généralement des connaissances techniques de la part d'un client revendu.

Cet atelier de programmation explique comment utiliser l'API Site Verification pour implémenter cette automatisation.

Avant de commencer

Cet atelier de programmation suppose également que vous avez terminé l'atelier de programmation sur le provisionnement de bout en bout de Workspace.

Présentation

La validation du domaine pour les droits d'accès Google Workspace implique plusieurs appels d'API.

Procédure à suivre pour automatiser la validation des domaines

L'API Site Verification n'est pas spécifique aux revendeurs. La validation de domaine est un signal utilisé dans divers produits Google (Search Console, Ads, etc.). La procédure décrite ici consiste à définir le super-administrateur du domaine de votre revendeur en tant que "propriétaire" du domaine et à définir le premier administrateur de votre client en tant que copropriétaire. Pour en savoir plus sur ces concepts, consultez la page Premiers pas avec l'API Site Verification.

Étape 1: Préparation à l'API de validation de site

Étape 2: Obtenir le jeton de validation

Cet atelier de programmation se concentre sur la méthode la plus courante pour valider un domaine: l'utilisation d'enregistrements DNS TXT. L'API de validation de site est compatible avec d'autres méthodes de validation.

Pour récupérer le jeton que vous allez placer en tant qu'enregistrement TXT, vous devez obtenir des jetons pour type=INET_DOMAIN et verificationMethod=DNS_TXT.

Dans le code suivant, renseignez ces variables à l'aide de vos informations.

  • jsonKeyFile : chemin d'accès au fichier de clé JSON généré lorsque vous avez créé un compte de service.
  • resellerAdminUser : adresse e-mail d'un super-administrateur de domaine de revendeur.
  • customerDomain: domaine du client final. Si vous exécutez cet atelier de programmation dans votre Console de vente pour les partenaires de test, assurez-vous que le domaine respecte les conventions d'attribution de noms.

C#

À l'aide des importations suivantes:

using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.SiteVerification.v1;
using Google.Apis.SiteVerification.v1.Data;

Créez le client API et récupérez le jeton:

// Set up credentials with user impersonation
ICredential credential = GoogleCredential.FromFile(jsonKeyFile)
                             .CreateScoped("https://www.googleapis.com/auth/siteverification")
                             .CreateWithUser(resellerAdminUser);

// Create the API service
var verificationService = new SiteVerificationService(new BaseClientService.Initializer{
    HttpClientInitializer = credential,
});

// Fetch the token
var request = new SiteVerificationWebResourceGettokenRequest {
  VerificationMethod = "DNS_TXT",
  Site = new SiteVerificationWebResourceGettokenRequest.SiteData {
    Type = "INET_DOMAIN",
    Identifier = customerDomain
  }
};
var response = verificationService.WebResource.GetToken(request).Execute();
string token = response.Token;
Console.WriteLine("Site Verification token: " + token);

Go

À l'aide des importations suivantes:

import (
  "context"
  "fmt"
  "os"

  "golang.org/x/oauth2/google"
  "google.golang.org/api/option"
  "google.golang.org/api/siteverification/v1"
)

Créez le client API et récupérez le jeton:

ctx := context.Background()

// Set up credentials with user impersonation
jsonKey, _ := os.ReadFile(jsonKeyFile)
jwt, _ := google.JWTConfigFromJSON(jsonKey, "https://www.googleapis.com/auth/siteverification")
jwt.Subject = resellerAdminUser
tokenSource := jwt.TokenSource(ctx)

// Create the API Service
verificationService, _ := siteverification.NewService(ctx, option.WithTokenSource(tokenSource))

// Fetch the token
req := &siteverification.SiteVerificationWebResourceGettokenRequest{
  Site: &siteverification.SiteVerificationWebResourceGettokenRequestSite{
    Type:       "INET_DOMAIN",
    Identifier: customerDomain,
  },
  VerificationMethod: "DNS_TXT",
}
res, _ := verificationService.WebResource.GetToken(req).Do()
token := res.Token
fmt.Println("Site verification token: " + token)

Java

À l'aide des importations suivantes:

import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.auth.oauth2.ServiceAccountCredentials;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.siteVerification.SiteVerification;
import com.google.api.services.siteVerification.SiteVerificationScopes;
import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenRequest;
import com.google.api.services.siteVerification.model.SiteVerificationWebResourceGettokenResponse;
import com.google.api.services.siteVerification.model.SiteVerificationWebResourceResource;
import java.io.FileInputStream;
import java.util.Arrays;

Créez le client API et récupérez le jeton:

// Set up credentials with user impersonation
FileInputStream jsonKeyFileSteam = new FileInputStream(JSON_KEY_FILE);
GoogleCredentials credentials = ServiceAccountCredentials.fromStream(jsonKeyFileSteam)
                                    .createScoped("https://www.googleapis.com/auth/siteverification")
                                    .createDelegated(RESELLER_ADMIN_USER);

// Create the API service
SiteVerification verificationService = new SiteVerification.Builder(
    GoogleNetHttpTransport.newTrustedTransport(),
    JacksonFactory.getDefaultInstance(),
    new HttpCredentialsAdapter(credentials)).build();

// Fetch the token
SiteVerificationWebResourceGettokenRequest request =
    new SiteVerificationWebResourceGettokenRequest()
        .setVerificationMethod("DNS_TXT")
        .setSite(new SiteVerificationWebResourceGettokenRequest.Site()
            .setType("INET_DOMAIN")
            .setIdentifier(CUSTOMER_DOMAIN));
SiteVerificationWebResourceGettokenResponse response =
    verificationService.webResource().getToken(request).execute();
String token = response.getToken();
System.out.println("Site Verification token: " + token);

Node.js

En utilisant l'importation suivante:

const {google} = require('googleapis');

Créez le client API et récupérez le jeton:

// Set up credentials with user impersonation
const authJWT = new JWT({
  keyFile: jsonKeyFile,
  scopes: ['https://www.googleapis.com/auth/siteverification'],
  subject: resellerAdminUser,
});

// Create the API service
const verificationService = google.siteVerification({version: 'v1', auth: authJWT});

// Fetch the token
const { data } = await verificationService.webResource.getToken({
  requestBody: {
    site: {
      type: 'INET_DOMAIN',
      identifier: customerDomain,
    },
    verificationMethod: 'DNS_TXT',
  }
});
const token = data.token;
console.log(`Site Verification token: ${token}`);

PHP

Créez le client API et récupérez le jeton:

// Set up credentials with user impersonation
$client = new Google_Client();
$client->setAuthConfig($JSON_KEY_FILE);
$client->setSubject($RESELLER_ADMIN_USER);
$client->setScopes('https://www.googleapis.com/auth/siteverification');

// Create the API service
$verificationService = new Google_Service_SiteVerification($client);

// Fetch the token
$request = new Google_Service_SiteVerification_SiteVerificationWebResourceGettokenRequest([
  'verificationMethod' => 'DNS_TXT',
  'site' => [
    'type' => 'INET_DOMAIN',
    'identifier' => $CUSTOMER_DOMAIN
  ]
]);
$response = $verificationService->webResource->getToken($request);
$token = $response->token;
print 'Site Verification token: ' . $token . PHP_EOL;

Python

À l'aide des importations suivantes:

from google.oauth2 import service_account
from apiclient.discovery import build

Créez le client API et récupérez le jeton:

# Set up credentials with user impersonation
credentials = service_account.Credentials.from_service_account_file(
    JSON_KEY_FILE, scopes=["https://www.googleapis.com/auth/siteverification"])
credentials_delegated = credentials.with_subject(RESELLER_ADMIN_USER)

# Create the API service
verification_service = build(serviceName="siteVerification", version="v1",
    credentials=credentials_delegated)

# Fetch the token
response = verification_service.webResource().getToken(
  body={
    "site": {
      "type": "INET_DOMAIN",
      "identifier": CUSTOMER_DOMAIN
    },
    "verificationMethod": "DNS_TXT"
  }).execute()
token = response["token"]
print("Site Verification token: " + token)

Étape 3: Placer le jeton de validation

Écrivez le code pour ajouter le jeton en tant qu'enregistrement TXT dans les enregistrements DNS du domaine du client.

Pour les nouveaux domaines, c'est le moment idéal pour configurer les enregistrements MX requis pour Gmail.

Étape 4: Déclencher la validation du domaine

Une fois le jeton placé en tant qu'enregistrement TXT, vous pouvez appeler l'API de validation de site pour déclencher la validation. Pour ce faire, appelez webResource.insert().

L'appel échoue avec une erreur 400 si le jeton attendu n'est pas trouvé. Vous pouvez implémenter une stratégie de nouvelle tentative avec une réduction exponentielle jusqu'à ce que l'appel aboutisse pour compenser les retards de propagation du DNS.

Si l'appel ne renvoie aucune erreur, l'API de validation de site considère le domaine comme validé et tous les e-mails du champ owners de webResource sont des propriétaires validés.

La propagation de l'état de validation dans le compte Google Workspace de votre client peut prendre environ trois heures. Vous pouvez forcer la propagation instantanée de l'état en définissant l'administrateur du client (créé lorsque vous avez appelé provisionCloudIdentity) en tant qu'owner de l'webResource.

C#

// Set the customer's admin user as an owner to make sure the domain
// verification status is instantly propagated to the Workspace account
string[] owners = { "admin@" + customerDomain };

var resource = new SiteVerificationWebResourceResource {
  Site = new SiteVerificationWebResourceResource.SiteData {
    Type = "INET_DOMAIN",
    Identifier = customerDomain
  },
  Owners = owners
};

resource = verificationService.WebResource.Insert(resource, "DNS_TXT").Execute();
Console.WriteLine("=== Domain has been verified");

Go

// Set the customer's admin user as an owner to make sure the domain
// verification status is instantly propagated to the Workspace account
resource := &siteverification.SiteVerificationWebResourceResource{
  Site: &siteverification.SiteVerificationWebResourceResourceSite{
    Type:       "INET_DOMAIN",
    Identifier: customerDomain,
  },
  Owners: []string{"admin@" + customerDomain},
}
resource, err := verificationService.WebResource.Insert("DNS_TXT", resource).Do()
if err != nil {
  fmt.Println(err)
} else {
  fmt.Println("=== Domain has been verified")
}

Java

// Set the customer's admin user as an owner to make sure the domain
// verification status is instantly propagated to the Workspace account
SiteVerificationWebResourceResource resource =
    new SiteVerificationWebResourceResource()
        .setSite(new SiteVerificationWebResourceResource.Site()
            .setIdentifier(CUSTOMER_DOMAIN)
            .setType("INET_DOMAIN"))
        .setOwners(Arrays.asList("admin@" + CUSTOMER_DOMAIN));

resource = verificationService.webResource().insert("DNS_TXT", resource).execute();
System.out.println("=== Domain has been verified");

Node.js

// Set the customer's admin user as an owner to make sure the domain
// verification status is instantly propagated to the Workspace account
await verificationService.webResource.insert({
  verificationMethod: 'DNS_TXT',
  requestBody: {
    site: {
      type: 'INET_DOMAIN',
      identifier: customerDomain,
    },
    owners: [`admin@${customerDomain}`],
  }
});
console.log('=== Domain has been verified');

PHP

// Set the customer's admin user as an owner to make sure the domain
// verification status is instantly propagated to the Workspace account
$resource = new Google_Service_SiteVerification_SiteVerificationWebResourceResource([
  'site' => [
    'type' => 'INET_DOMAIN',
    'identifier' => $CUSTOMER_DOMAIN,
  ],
  'owners' => ['admin@' . $CUSTOMER_DOMAIN]
]);

$resource = $verificationService->webResource->insert('DNS_TXT', $resource);
print '=== Domain has been verified' . PHP_EOL;

Python

# Set the customer's admin user as an owner to make sure the domain
# verification status is instantly propagated to the Workspace account
resource = verification_service.webResource().insert(
  verificationMethod="DNS_TXT",
  body={
    "site": {
      "type": "INET_DOMAIN",
      "identifier": CUSTOMER_DOMAIN
    },
    "owners": ["admin@" + CUSTOMER_DOMAIN]
  }).execute()
print("=== Domain has been verified")