Skip to content

Instantly share code, notes, and snippets.

@TawsifKarim
Last active December 21, 2022 07:10
Show Gist options
  • Select an option

  • Save TawsifKarim/2528fe060d19d506318b3cc80abaaffa to your computer and use it in GitHub Desktop.

Select an option

Save TawsifKarim/2528fe060d19d506318b3cc80abaaffa to your computer and use it in GitHub Desktop.
SignIn With Google Implementation using Nuxt Js, Golang And Laravel 2022

frontend Part

in your component

export default{
head () {
    return {
      script: [
        {
          src: 'https://accounts.google.com/gsi/client',
          type: 'text/javascript',
          async: true,
          defer: true
        }
      ]
    }
  },
    methods: {
       handleCredentialResponse(response) {
          console.log("Encoded JWT ID token: " + response.credential); //SEND THIS TOKEN TO YOUR BACKEND SERVER
        }
    }, 
    mounted(){
      google.accounts.id.initialize({
            client_id: "YOUR_CLIENT_ID_OBTAINED_FROM_GOOGLE_DEVELOPER_CONSOLE",
            callback: this.handleCredentialResponse
          });
          google.accounts.id.renderButton(
            document.getElementById("buttonDiv"), //Dont forget to create this button: <div id="buttonDiv"></div>
            { theme: "outline", size: "large" }  // customization attributes
          );
          google.accounts.id.prompt(); // also display the One Tap dialog
    }
  }

If you are using laravel

composer require google/apiclient:^2.12.1

In your .php file
Route::post('google-jwt-token', function(){
  `$id_token = "TOKEN_SENT_FROM_NUXT_JS(FRONTEND)_APP";`
  $CLIENT_ID = "YOUR_CLIENT_ID_OBTAINED_FROM_GOOGLE_DEVELOPER_CONSOLE";
  $client = new Google_Client(['client_id' => $CLIENT_ID]);  // Specify the CLIENT_ID of the app that accesses the backend
  $payload = $client->verifyIdToken($id_token);
  if ($payload) {
      $userid = $payload['sub'];
      // If request specified a G Suite domain:
      //$domain = $payload['hd'];
      return response()->json($payload, 200);
  } else {
      // Invalid ID token
      return response()->json(['invalid token'], 200);
  }
});

If you are using golang server

go get google.golang.org/api/idtoken

in your go file
ctx := context.Background()
	token := "TOKEN_SENT_FROM_NUXTJS_FRONTEND_APP"
	clientID := "YOUR_CLIENT_ID_OBTAINED_FROM_GOOGLE_DEVELOPER_CONSOLE"
  
  payload, err := idtoken.Validate(ctx, token, clientID)
	if err != nil {
		fmt.Println("error in validating")
    os.Exit(-1)
	}
  fmt.Println(payload.Claims)

The tokens are shortlived. So always check if err != nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment