> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuration de l'authentification PlayFab avec Google et HTML5

> Tutoriel étape par étape pour ajouter la connexion Google à un titre PlayFab à l'aide de HTML5 et JavaScript, couvrant la configuration de l'API Google et l'authentification OAuth des joueurs.

Ce tutoriel vous guide dans le processus d'authentification PlayFab à l'aide de Google et de HTML5/JavaScript.

## Exigences

Vous aurez besoin de :

* Un [compte Google](https://google.com/) pour les tests.
* Un titre `[PlayFab](https://developer.playfab.com/)` inscrit.
* Une bonne connaissance des [principes de base et meilleures pratiques de connexion](/fr-CA/services/playfab/identity/player-identity/login/login-basics-best-practices).
* Au minimum, un serveur avec un nom de domaine valide pour servir un fichier HTML statique. Consultez le tutoriel [Exécution d'un serveur HTTP pour les tests](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) pour savoir comment en configurer un.

## Serveur et domaine

Ce guide nécessite un serveur avec un domaine valide. Si vous n'avez pas encore de domaine inscrit ni de serveur Web distant, suivez notre tutoriel [Exécution d'un serveur HTTP pour les tests](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) pour savoir comment exécuter un serveur Web local avec un nom de domaine valide.

Tout au long de ce guide, nous supposerons que votre domaine est `[http://playfab.example](http://playfab.example)`.

## Inscription d'un projet d'API Google

Commencez par accéder à la [console des API Google](https://console.developers.google.com/) :

1. Accédez à **CREATE PROJECT** et sélectionnez-le.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-project.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=5b9ba00fd573b49ddbdc0a4b47d173a4" alt="Google API Manager - créer de nouvelles informations d'identification" width="1607" height="426" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-project.png" />

1. Remplissez le champ sous **Project Name**.
2. Sélectionnez le bouton **Create**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-new-project.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=10b5bb3e56749cdc940cc756f0285d0d" alt="Google API Manager - nouveau projet" width="1607" height="605" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-new-project.png" />

<Note>
  Il est normal que l'**API Manager** prenne de 10 à 20 secondes pour générer le projet.
</Note>

Une fois le projet créé :

1. Accédez à l'**OAuth consent screen**.
2. Sélectionnez **External** sous User Type
3. Sélectionnez ensuite **Create**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-consent-screen.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=f6889444d347b1f9d78f0309c2e75193" alt="Google API Manager - écran de consentement OAuth" width="965" height="652" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-consent-screen.png" />

1. Remplissez un nom d'application (App Name)
2. Assurez-vous que des adresses courriel sont indiquées pour **user support email** et **Developer Contact Email**
3. Sélectionnez ensuite **SAVE AND CONTINUE**

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-consent-screen-1.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=f3d7855e3f4b8ecd65cf3eb41f8f358c" alt="Google API Manager - configuration de l'écran de consentement OAuth" width="1607" height="1030" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-consent-screen-1.png" />

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-consent-screen-2.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=d6013db1014b105eae236b04f61a92b9" alt="Google API Manager - configuration de l'écran de consentement OAuth 2" width="1607" height="1030" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-consent-screen-2.png" />

1. Accédez ensuite à **Credentials**.
2. Sélectionnez **Create credentials**.
3. Sélectionnez ensuite **OAuth client ID**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-oauth-credentials.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=6d594083a2d96943f337a0c2489c40eb" alt="Google API Manager - ouvrir les informations d'identification OAuth" width="1145" height="536" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-oauth-credentials.png" />

1. Sélectionnez **Web Application** comme **Application type**.
2. Donnez un **Name** à votre application.
3. Ajoutez votre domaine à **Authorized JavaScript origins**  - `[PlayFab](http://playfab.example.com)` dans notre cas.
4. Enfin, sélectionnez le bouton **Create** pour valider vos modifications.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-credentials.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=0cc913b14a6883d7f2286121ce8af563" alt="Google API Manager - créer des informations d'identification OAuth" width="1607" height="1030" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-credentials.png" />

Sur l'écran **OAuth client** illustré ci-dessous, le Google API Manager révèle deux informations importantes :

1. Le **client ID**
2. Le **client secret**.

<Note>
  Assurez-vous de copier et d'enregistrer ces valeurs dans un endroit sûr et facilement accessible, car elles seront utilisées dans le processus d'autorisation présenté plus loin dans ce tutoriel.
</Note>

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-client-credentials.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=33427703b3ddb679666f2d4c0632e0c8" alt="Google API Manager - ID client et secret OAuth" width="549" height="577" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-client-credentials.png" />

Accédez à la page **Game Manager** de PlayFab pour votre titre.

1. Accédez à **Add-ons** dans le menu.
2. Repérez et ouvrez l'icône ou le lien **Google Add-on**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-google-add-on.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=1b0af874b0d7e46cf30337e322f0004a" alt="Module complémentaire PlayFab Game Manager" width="1589" height="1043" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-google-add-on.png" />

1. Remplissez le **Client ID**.
2. Remplissez le **Client secret**.
3. Sélectionnez ensuite le bouton **Install Google**.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/install-google-add-on.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=d84b1601417c536b97d909df1ae1f58c" alt="PlayFab Game Manager - installer le module complémentaire Google" width="1135" height="700" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/install-google-add-on.png" />

<Note>
  Depuis juillet 2017, le **Google API Manager** a la mauvaise habitude de *ne pas* associer correctement le domaine d'origine **Allowed JS**. Si vous recevez l'erreur suivante : **"idpiframe\_initialization\_failed", details: "Not a valid origin for the client: somedomain.com..."**, supprimez les informations d'identification et recréez-les. *Il n'est pas nécessaire de supprimer tout le projet, seulement les informations d'identification.*
</Note>

## Test à l'aide d'un jeton d'accès

Dans cet exemple, nous montrons comment tester l'API LoginWithGoogleAccount à l'aide de l'approche classique par jeton d'accès. Utilisez le code HTML fourni ci-dessous pour vos tests.

<Note>
  Assurez-vous\* de remplacer `YOUR_CLIENT_ID` et `YOUR_PLAYFAB_TITLE` par vos propres valeurs.
</Note>

<Note>
  le paramètre **AccessToken** est absent de l'objet **LoginWithGoogleAccountRequest** dans les fichiers de typage TypeScript. Si vous utilisez TypeScript avec le Node SDK, vous pouvez créer un type personnalisé `interface LoginRequest extends PlayFabClientModels.LoginWithGoogleAccountRequest { AccessToken: string; }` et convertir le type lors de l'utilisation de l'API `PlayFabClient.LoginWithGoogleAccount( { AccessToken: accessToken, CreateAccount: true, } as LoginRequest, onPlayFabResponse);`
</Note>

```html theme={null}
<!DOCTYPE html>
<html>
  <head>
    <script src="https://accounts.google.com/gsi/client" onload="initClient()" async defer></script>
    <script src="https://download.playfab.com/PlayFabClientApi.js"></script>
  </head>
  <body>
    <script>
      var client;
      function initClient() {
          console.log("Initializing Google token client on page load");
          client = google.accounts.oauth2.initTokenClient({
              client_id: "YOUR_CLIENT_ID", // TODO: PUT YOUR GOOGLE CLIENT_ID HERE!
              callback: "onTokenResponse",
              scope: "https://www.googleapis.com/auth/userinfo.profile",
              callback: (tokenResponse) => {
                  access_token = tokenResponse.access_token;
                  onSignIn();
              }
          });
      }

      function getToken() {
        client.requestAccessToken();
      }

      // Invoked after user has signed in with Google
      function onSignIn() {
          // Execute LoginWithGoogleAccount API call using the Google access token. Please replace TitleId.
          logLine("Attempting PlayFab Sign-in using LoginWithGoogleAccount");
          PlayFabClientSDK.LoginWithGoogleAccount({
              AccessToken: access_token, // This access token is generated after a user has signed into Google
              CreateAccount: true,
              TitleId: "YOUR_PLAYFAB_TITLE", // TODO: PUT YOUR TITLE ID HERE!
          }, onPlayFabResponse);
      }

      // Handles response from PlayFab
      function onPlayFabResponse(response, error) {
          if (response)
              logLine("Response: " + JSON.stringify(response));
          if (error)
              logLine("Error: " + JSON.stringify(error));
      }

      function logLine(message) {
          var textnode = document.createTextNode(message);
          document.body.appendChild(textnode);
          var br = document.createElement("br");
          document.body.appendChild(br);
      }
    </script>
    <h1>Google Access Token Auth Example</h1>
    <!-- Clicking this button will prompt the user to sign into Google. Once they have signed into Google, LoginWithGoogleAccount is automatically called. -->
    <button onclick="getToken();">Sign into Google</button><br><br>
  </body>
</html>
```

**Test à l'aide de la bibliothèque Google Sign-in Platform (dépréciée)**

<Note>
  L'exemple ci-dessous utilise la bibliothèque de plateforme Google Sign-In. **Selon le [site de documentation publique de Google Identity](https://developers.google.com/identity/gsi/web/guides/migration), la bibliothèque de plateforme JavaScript Google Sign-In pour le Web sera dépréciée le 31 mars 2023**. Cet exemple ne fonctionnera pas pour les nouveaux clients Google créés à l'avenir; consultez l'exemple de code précédent, qui utilise la bibliothèque Google Identity Services plus récente!
</Note>

```html theme={null}
<!DOCTYPE html>
<html>
<head>
    <!-- Special meta tag allows you to pass Google Client ID. Replace the content attribute value with your own Client Id -->
    <meta name="google-signin-client_id" content="YOUR_CLIENT_ID"><!-- // TODO: PUT YOUR GOOGLE CLIENT_ID HERE! -->
    <!-- Load Google platform SDK-->
    <script src="https://apis.google.com/js/platform.js" async defer></script>
    <!-- Load PlayFab Client JavaScript SDK -->
    <script src="https://download.playfab.com/PlayFabClientApi.js"></script>
</head>
<body>
    <p>Google Access Token Auth Example</p>
    <!-- Neat Google button gets styled automatically when Google platform SDK is loaded -->
    <div class="g-signin2" data-onsuccess="onSignIn"></div>
    <script>
        // Invoked when user has signed in with Google
        function onSignIn() {
            // Retrieve access token
            var accessToken = gapi.auth2.getAuthInstance().currentUser.get().getAuthResponse(true).access_token;
            // Execute LoginWithGoogleAccount API call using the access token. Please replace TitleID with your own.
            logLine("Attempting PlayFab Sign-in using LoginWithGoogleAccount");
            PlayFabClientSDK.LoginWithGoogleAccount({
                ServerAuthCode: accessToken,
                CreateAccount : true,
                TitleId: "YOUR_PLAYFAB_TITLE", // TODO: PUT YOUR TITLE ID HERE!
            }, onPlayFabResponse);
        }

        // Handles response from PlayFab
        function onPlayFabResponse(response, error) {
            if (response)
                logLine("Response: " + JSON.stringify(response));
            if (error)
                logLine("Error: " + JSON.stringify(error));
        }

        function logLine(message) {
            var textnode = document.createTextNode(message);
            document.body.appendChild(textnode);
            var br = document.createElement("br");
            document.body.appendChild(br);
        }
    </script>
</body>
</html>
```

N'oubliez pas d'ouvrir cette page à l'aide de votre serveur Web, et assurez-vous d'y accéder à l'aide de l'URL que vous avez spécifiée lors de la configuration du projet Google (`http://playfab.example` dans notre cas).

1. Une fois la page ouverte, sélectionnez **G Signed In** et suivez le flux d'authentification Google habituel.
2. Une fois cela terminé, le script tentera de s'authentifier du côté de PlayFab et affichera le résultat.

<img src="https://mintcdn.com/microsoft-4404708b/mLCHf0iQv3VidfBe/images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/google-auth-example.png?fit=max&auto=format&n=mLCHf0iQv3VidfBe&q=85&s=b931669ffe5a96cb90404383ab650072" alt="Exemple d'authentification Google" width="568" height="339" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/google-auth-example.png" />

<Note>
  Si vous avez *déjà* une session d'authentification Google en cours, vous n'aurez pas à sélectionner **G Signed In**. Tout se fera automatiquement.
</Note>


## Related topics

- [Authentification propre à la plateforme](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
- [Configuration de l'authentification PlayFab avec Kongregate et HTML5](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/kongregate-html5.md)
- [Configuration de l'authentification PlayFab avec Facebook et HTML5](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/facebook-html5.md)
- [Configuration de l'authentification PlayFab avec Twitch et HTML5](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/twitch-html5.md)
- [Authentification par connexion anonyme côté serveur](/fr-CA/services/playfab/identity/player-identity/platform-specific-authentication/anonymous-login.md)
