> ## 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.

# Configuración de la autenticación de PlayFab con Google y HTML5

> Tutorial paso a paso para agregar el inicio de sesión de Google a un título de PlayFab mediante HTML5 y JavaScript, que abarca la configuración de la API de Google y la autenticación de jugadores con OAuth.

Este tutorial le guía a través del proceso de autenticación de PlayFab con Google y HTML5/JavaScript.

## Requisitos

Necesitará:

* Una [cuenta de Google](https://google.com/) para realizar pruebas.
* Un título de `[PlayFab](https://developer.playfab.com/)` registrado.
* Familiaridad con [Conceptos básicos de inicio de sesión y procedimientos recomendados](/services/playfab/identity/player-identity/login/login-basics-best-practices).
* Como mínimo, un servidor con un nombre de dominio válido que actúe como archivo HTML estático. Consulte el tutorial [Ejecución de un servidor HTTP para pruebas](/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obtener información sobre cómo configurar uno.

## Servidor y dominio

Para seguir esta guía se necesita un servidor con un dominio válido. Si aún no tiene un dominio registrado y un servidor web remoto, siga nuestro tutorial [Ejecución de un servidor HTTP para pruebas](/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obtener información sobre cómo configurar uno para ejecutar un servidor web local con un nombre de dominio válido.

A lo largo de esta guía, supondremos que su dominio es `[http://playfab.example](http://playfab.example)`.

## Registro de un proyecto de la API de Google

Comience por ir a la [consola de la API de Google](https://console.developers.google.com/):

1. Vaya a **CREATE PROJECT** y selecciónelo.

<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="Crear nuevas credenciales en el Administrador de API de Google" width="1607" height="426" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-project.png" />

1. Rellene el campo situado bajo **Project Name**.
2. Seleccione el botón **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="Nuevo proyecto en el Administrador de API de Google" width="1607" height="605" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-new-project.png" />

<Note>
  Es normal que el **Administrador de API** tarde entre 10 y 20 segundos en generar el proyecto.
</Note>

Una vez creado el proyecto:

1. Vaya a la **pantalla de consentimiento de OAuth**.
2. Seleccione **External** en User Type.
3. A continuación, seleccione **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="Pantalla de consentimiento de OAuth del Administrador de API de Google" width="965" height="652" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-consent-screen.png" />

1. Rellene un nombre de aplicación.
2. Asegúrese de que hay correos electrónicos en **user support email** y **Developer Contact Email**.
3. A continuación, seleccione **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="Configuración de la pantalla de consentimiento de OAuth del Administrador de API de Google" 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="Configuración de la pantalla de consentimiento de OAuth del Administrador de API de Google 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. A continuación, vaya a **Credentials**.
2. Seleccione **Create credentials**.
3. Después, seleccione **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="Abrir credenciales de OAuth en el Administrador de API de Google" width="1145" height="536" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-oauth-credentials.png" />

1. Seleccione **Web Application** como **Application type**.
2. Asigne un **nombre** a la aplicación.
3. Agregue su dominio a **Authorized JavaScript origins**, `[PlayFab](http://playfab.example.com)` en nuestro caso.
4. Por último, seleccione el botón **Create** para confirmar los cambios.

<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="Crear credenciales de OAuth en el Administrador de API de Google" width="1607" height="1030" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-credentials.png" />

En la pantalla **OAuth client** que se muestra a continuación, el Administrador de API de Google revela dos datos importantes:

1. El **identificador de cliente**.
2. El **secreto de cliente**.

<Note>
  Asegúrese de copiar y guardar estos valores en un lugar seguro de fácil acceso, ya que se usarán en el proceso de autorización que se muestra más adelante en este tutorial.
</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="Identificador de cliente y secreto de OAuth del Administrador de API de Google" width="549" height="577" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-client-credentials.png" />

Vaya a la página de **Game Manager** de PlayFab de su título.

1. Vaya a **Add-ons** en el menú.
2. Busque y abra el icono o vínculo del **complemento de Google**.

<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="Complemento de Game Manager de PlayFab" width="1589" height="1043" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-google-add-on.png" />

1. Rellene el **identificador de cliente**.
2. Rellene el **secreto de cliente**.
3. A continuación, seleccione el botón **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="Instalar el complemento de Google en Game Manager de PlayFab" width="1135" height="700" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/install-google-add-on.png" />

<Note>
  Desde julio de 2017, el **Administrador de API de Google** tiene la mala costumbre de *no* enlazar correctamente el dominio de origen de **Allowed JS**. Si recibe el error siguiente: **"idpiframe\_initialization\_failed", details: "Not a valid origin for the client: somedomain.com..."**, elimine las credenciales y vuelva a crearlas. *No es necesario eliminar todo el proyecto, solo las credenciales.*
</Note>

## Pruebas con un token de acceso

En este ejemplo, mostramos cómo probar la API LoginWithGoogleAccount mediante el enfoque clásico de token de acceso. Use el código HTML que se proporciona a continuación para sus pruebas.

<Note>
  Asegúrese\* de reemplazar `YOUR_CLIENT_ID` y `YOUR_PLAYFAB_TITLE` por sus propios valores.
</Note>

<Note>
  El parámetro **AccessToken** falta en el objeto **LoginWithGoogleAccountRequest** de los archivos de tipos de TypeScript. Si usa TypeScript con el SDK de Node, puede crear un tipo personalizado `interface LoginRequest extends PlayFabClientModels.LoginWithGoogleAccountRequest { AccessToken: string; }` y convertir el tipo al usar la 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>
```

**Pruebas con la biblioteca (en desuso) de Google Sign-in Platform**

<Note>
  El ejemplo siguiente usa la biblioteca de plataforma de Google Sign-In. **Según el [sitio de documentación pública de Google Identity](https://developers.google.com/identity/gsi/web/guides/migration), la biblioteca de plataforma de JavaScript de Google Sign-In para web quedará en desuso el 31 de marzo de 2023**. Este ejemplo no funcionará para los clientes de Google recién creados de aquí en adelante; consulte el ejemplo de código anterior, que usa la biblioteca más reciente de Google Identity Services.
</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>
```

Recuerde abrir esta página con su servidor web y asegúrese de acceder a ella mediante la URL que especificó al configurar el proyecto de Google (`http://playfab.example` en nuestro caso).

1. Cuando se abra la página, seleccione **G Signed In** y siga el flujo general de autenticación de Google.
2. Cuando esto termine, el script intentará autenticarse en PlayFab y mostrará el resultado.

<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="Ejemplo de autenticación de Google" width="568" height="339" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/google-auth-example.png" />

<Note>
  Si *ya tiene* una sesión de autenticación de Google en ejecución, no tendrá que seleccionar **G Signed In**. Todo sucederá automáticamente.
</Note>


## Related topics

- [Autenticación específica de la plataforma](/es/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
- [Configuración de la autenticación de PlayFab con Kongregate y HTML5](/es/services/playfab/identity/player-identity/platform-specific-authentication/kongregate-html5.md)
- [Configuración de la autenticación de PlayFab con Twitch y HTML5](/es/services/playfab/identity/player-identity/platform-specific-authentication/twitch-html5.md)
- [Configuración de la autenticación de PlayFab mediante Facebook y HTML5](/es/services/playfab/identity/player-identity/platform-specific-authentication/facebook-html5.md)
- [Configuración del inicio de sesión con Battle.net para PlayFab](/es/services/playfab/identity/player-identity/platform-specific-authentication/battlenet-login.md)
