Instagram
youtube
Facebook
  • 1 year, 8 months ago
  • 2809 Views

Google Authentication with Golang and Goth

Yaman Birla
Table of Contents

Here in this article we have goth multi provider authentication package of go to create google authentication using Golang. We have used google OAuth for Golang using goth multi provider.

In this Article, we’ll be implementing authentication via google using golang web application and we will be using Goth - Multi-Provider Authentication Package for Go. goth provides a simple, clean way to write authentication packages for Go web applications. 

 

Before proceeding further make sure to have the following in your computer and have at least basic knowledge of these technologies:

  • HTML, CSS.
  • Go Language.
  • Golang installed on your computer with the latest version.

 

Now, Firstly, we need to create a Google client ID and client secret and to do this open Google API console and head over to the project drop down and select the existing project or create a new project.

Now, head over to the sidebar in “API & Services” select credentials.

Choose OAuth client ID from the Create credentials drop-down list on the Credentials tab.

Choose Web application under Application type.

Utilize http://localhost:3000/auth/google/callback in the Authorized redirect URI.

Copy the created client ID and client secret by pressing the Create button.

 

Now, we’ll head over to create our server code in Golang. So, in the command prompt run the following command “go mod init googleauth”.

This will create a go.mod file and automatically imports the packages when you run the go program.

 

Now, create a file named main.go under your root folder of the app, and add the given code below:

____________________________________________________________

package main

import (
	"fmt"
	"html/template"
	"net/http"

	"log"

	"github.com/gorilla/pat"
	"github.com/gorilla/sessions"
	"github.com/markbates/goth"
	"github.com/markbates/goth/gothic"
	"github.com/markbates/goth/providers/google"
)

func main() {

	key := "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" //your client secret
	maxAge := 86400 * 30 // 30 days
	isProd := true       // Set to true when serving over https

	store := sessions.NewCookieStore([]byte(key))
	store.MaxAge(maxAge)
	store.Options.Path = "/"
	store.Options.HttpOnly = true // HttpOnly should always be enabled
	store.Options.Secure = isProd

	gothic.Store = store

	goth.UseProviders(
		google.New("623077223352-dbv82pd0qo18i145dlo0up8n4lihpv1j.apps.googleusercontent.com", "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", "http://localhost:3000/auth/google/callback", "email", "profile"),
	)

	p := pat.New()
	p.Get("/auth/{provider}/callback", func(res http.ResponseWriter, req *http.Request) {

		user, err := gothic.CompleteUserAuth(res, req)
		if err != nil {
			fmt.Fprintln(res, err)
			return
		}
		t, _ := template.ParseFiles("templates/success.html")
		t.Execute(res, user)
	})

	p.Get("/auth/{provider}", func(res http.ResponseWriter, req *http.Request) {
		gothic.BeginAuthHandler(res, req)
	})

	p.Get("/", func(res http.ResponseWriter, req *http.Request) {
		t, _ := template.ParseFiles("templates/index.html")
		t.Execute(res, false)
	})
	log.Println("listening on localhost:3000")
	log.Fatal(http.ListenAndServe(":3000", p))
}

____________________________________________________________




 

The packages that we have imported in our code has some small description below:

 

  • gorilla/pat: A lightweight HTTP router for Go
  • markbates/goth: Multi-Provider Authentication Package for Go
  • gorilla/sessions: To save information from google in session and use it on the success page
  • markbates/goth/providers/google: Google authentication provider by Goth
  • html/template: Go package to parse Html files

 

Some of the description of our code is here below:

 

  • "/": The root route will render the index.html page.

 

  • /auth/{provider}: When you click on the SignIn button it will hit this route and gothic.BeginAuthHandler will redirect you to google authentication URL.

 

  • /auth/{provider}/callback: Once you have authenticated Google will send all the user details on this callback URL, and goth will save the info in session also which can be used in other routes also if needed.


 

Now, we’ll create our Login and profile display page. Under the path in your project folder create an html file templates/index.html and add the following code:

____________________________________________________________

<!-- templates/index.html-->

<!doctype html>

<html>

    <head>

        <title>Google SignIn</title>

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- load bulma css-->

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- load fontawesome -->

    <style>

        body        { padding-top:70px; }

    </style>

    </head>

    <body>

        <div class="container">

            <div class="jumbotron text-center text-success">

                <h1><span class="fa fa-lock"></span> Social Authentication</h1>

                <p>Login or Register with:</p>

                <a href="/auth/google" class="btn btn-danger"><span class="fa fa-google"></span> SignIn with Google</a>

            </div>

        </div>

        </body>

</html>

 

____________________________________________________________

 

Now, similarly we’ll create a success.html file under the path templates/success.html and add the following code:

 

____________________________________________________________

<!-- templates/success.html -->

<!doctype html>

<html>

  <head>

    <title>Google SignIn</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- load bulma css -->

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- load fontawesome -->

      <style>

          body        { padding-top:70px; }

      </style>

  </head>

  <body>

    <div class="container">

      <div class="jumbotron">

          <h1 class="text-success  text-center"><span class="fa fa-user"></span> Profile Information</h1>

          <div class="row">

            <div class="col-sm-6">

                <div class="well">

                        <p>

                            <strong>Id</strong>: {{.UserID}}<br>

                            <strong>Email</strong>: {{.Email}}<br>

                            <strong>Name</strong>: {{.Name}}

                        </p>

                </div>

            </div>

        </div>

      </div>

    </div>

  </body>

</html>

____________________________________________________________



 

Now, it’s time to check our app and run the command “go run main.go”

You can check your login page on “ http://localhost:3000/

 

 

After clicking on the sign in we’ll redirect to google sign in page.

 

After signing in we will be redirected into our success page, where we can see the details of the logged in user.

 

 

Github: https://github.com/cosmic-weber/Golang/tree/main/go-workspace


 

Add a comment: