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

# Configurar a autenticação do PlayFab usando Google e HTML5

> Tutorial passo a passo para adicionar a entrada com o Google a um título do PlayFab usando HTML5 e JavaScript, abordando a configuração da API do Google e a autenticação de jogadores com OAuth.

Este tutorial orienta você no processo de autenticação do PlayFab usando Google e HTML5/JavaScript.

## Requisitos

Você precisará de:

* Uma [conta do Google](https://google.com/) para testes.
* Um título do `[PlayFab](https://developer.playfab.com/)` registrado.
* Familiaridade com os [conceitos básicos e práticas recomendadas de login](/pt-BR/services/playfab/identity/player-identity/login/login-basics-best-practices).
* No mínimo, um servidor com um nome de domínio válido para servir um arquivo HTML estático. Consulte o tutorial [Executar um servidor HTTP para testes](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obter informações sobre como configurar um.

## Servidor e domínio

Este guia requer um servidor com um domínio válido. Se você ainda não tiver um domínio registrado e um servidor Web remoto, siga nosso tutorial [Executar um servidor HTTP para testes](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/running-an-http-server-for-testing) para obter informações sobre como configurar e executar um servidor Web local com um nome de domínio válido.

Ao longo deste guia, presumiremos que seu domínio é `[http://playfab.example](http://playfab.example)`.

## Registrar um projeto da API do Google

Comece navegando até o [Console de APIs do Google](https://console.developers.google.com/):

1. Navegue até **CREATE PROJECT** e selecione essa opção.

<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="Gerenciador de APIs do Google: criar novas credenciais" width="1607" height="426" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-project.png" />

1. Preencha o campo em **Project Name**.
2. Selecione o botão **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="Gerenciador de APIs do Google: novo projeto" width="1607" height="605" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-new-project.png" />

<Note>
  É normal que o **API Manager** leve de 10 a 20 segundos para gerar o projeto.
</Note>

Depois que o projeto for criado:

1. Navegue até **OAuth consent screen**.
2. Selecione **External** em User Type
3. Em seguida, selecione **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="Gerenciador de APIs do Google: tela de consentimento OAuth" width="965" height="652" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-consent-screen.png" />

1. Preencha um nome de aplicativo (App Name)
2. Certifique-se de que haja emails em **user support email** e **Developer Contact Email**
3. Em seguida, selecione **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="Configuração da tela de consentimento OAuth no Gerenciador de APIs do 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="Configuração da tela de consentimento OAuth no Gerenciador de APIs do 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. Em seguida, navegue até **Credentials**.
2. Selecione **Create credentials**.
3. Em seguida, selecione **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="Gerenciador de APIs do Google: abrir credenciais OAuth" width="1145" height="536" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-oauth-credentials.png" />

1. Selecione **Web Application** como seu **Application type**.
2. Dê um **Name** ao seu aplicativo.
3. Adicione seu domínio a **Authorized JavaScript origins** - `[PlayFab](http://playfab.example.com)` no nosso caso.
4. Por fim, selecione o botão **Create** para confirmar suas alterações.

<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="Gerenciador de APIs do Google: criar credenciais OAuth" width="1607" height="1030" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/create-oauth-credentials.png" />

Na tela **OAuth client** mostrada abaixo, o Gerenciador de APIs do Google revela duas informações importantes:

1. A **client ID**
2. O **client secret**.

<Note>
  Certifique-se de copiar e salvar esses valores em um local seguro e de fácil acesso, pois eles serão usados no processo de autorização mostrado mais adiante neste 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="ID e segredo do cliente OAuth no Gerenciador de APIs do Google" width="549" height="577" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/oauth-client-credentials.png" />

Acesse a página do **Game Manager** do PlayFab para seu título.

1. Navegue até **Add-ons** no menu.
2. Localize e abra o ícone/link **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="Complemento do Game Manager do PlayFab" width="1589" height="1043" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/open-google-add-on.png" />

1. Preencha a **Client ID**.
2. Preencha o **Client secret**.
3. Em seguida, selecione o botão **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 o complemento do Google no Game Manager do 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 julho de 2017, o **Google API Manager** tem o mau hábito de *não* vincular corretamente o domínio de origem **Allowed JS**. Se você receber o seguinte erro: **"idpiframe\_initialization\_failed", details: "Not a valid origin for the client: somedomain.com..."**, remova as credenciais e recrie-as. *Não é necessário excluir o projeto inteiro, apenas as credenciais.*
</Note>

## Testar usando um token de acesso

Neste exemplo, mostramos como testar a API LoginWithGoogleAccount usando a abordagem clássica de token de acesso. Use o código HTML fornecido abaixo para seus testes.

<Note>
  Certifique-se\* de substituir `YOUR_CLIENT_ID` e `YOUR_PLAYFAB_TITLE` pelos seus próprios valores.
</Note>

<Note>
  o parâmetro **AccessToken** está ausente no objeto **LoginWithGoogleAccountRequest** nos arquivos de tipagem do TypeScript. Se você estiver usando TypeScript com o SDK do Node, poderá criar um tipo personalizado `interface LoginRequest extends PlayFabClientModels.LoginWithGoogleAccountRequest { AccessToken: string; }` e converter o tipo ao usar a 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>
```

**Testar usando a biblioteca Google Sign-in Platform (preterida)**

<Note>
  O exemplo abaixo usa a biblioteca da plataforma Google Sign-In. **De acordo com o [site de documentação pública do Google Identity](https://developers.google.com/identity/gsi/web/guides/migration), a biblioteca da plataforma JavaScript Google Sign-In para Web será preterida em 31 de março de 2023**. Este exemplo não funcionará para clientes do Google criados daqui em diante. Consulte o exemplo de código anterior, que usa a biblioteca mais recente 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>
```

Lembre-se de abrir esta página usando seu servidor Web e certifique-se de acessá-la usando a URL que você especificou ao configurar o projeto do Google (`http://playfab.example` no nosso caso).

1. Quando a página abrir, selecione **G Signed In** e siga o fluxo geral de autenticação do Google.
2. Quando isso terminar, o script tentará se autenticar no lado do PlayFab e exibirá o 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="Exemplo de autenticação do Google" width="568" height="339" data-path="images/playfab/identity/player-identity/platform-specific-authentication/tutorials/google-html5/google-auth-example.png" />

<Note>
  Se você *já tiver* uma sessão de autenticação do Google em execução, não será necessário selecionar **G Signed In**. Tudo acontecerá automaticamente.
</Note>


## Related topics

- [Autenticação específica da plataforma](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/index.md)
- [Configurar a autenticação do PlayFab usando Kongregate e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/kongregate-html5.md)
- [Configurar a autenticação do PlayFab usando Twitch e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/twitch-html5.md)
- [Configurar a autenticação do PlayFab usando Facebook e HTML5](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/facebook-html5.md)
- [Configurar a entrada com Battle.net para o PlayFab](/pt-BR/services/playfab/identity/player-identity/platform-specific-authentication/battlenet-login.md)
