Instagram
youtube
Facebook

Twitter Authentication in Golang

In this Article, We’ll be implementing Twitter Authentication using the Golang web application for this we will be using Goth which is social authentication middleware for Golang.

In this Article, We’ll be implementing Twitter Authentication using the Golang web application for this we will be using Goth which is social authentication middleware for Golang.

Before, proceeding further let’s check the prerequisites for this implementation. 

  • Basic knowledge of HTML is necessary.
  • Golang should be installed on your computer with the latest version.
  • Head over to the Twitter Developer portal and create a new Twitter app using application management and copy the API Key and Secret Key that have been generated for you. Don’t forget to add “127.0.0.1” in place of “localhost” because Twitter doesn’t seem to work well with localhost.
  • Make sure to set up the User Authentication settings on developer portal in Twitter.

 

Now, create a directory on your computer for the Go web application which includes main.go file and a folder named templates which consists of two HTML files one is index.html which works as Login UI and the other is success.html which works as our Profile UI.

 

In the index.html file add the following code:

 


<!doctype html>

<html>

<head>

    <title>Twitter 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/twitter" class="btn btn-danger"><span class="fa fa-twitter"></span> SignIn with Twitter</a>

    </div>

</div>

</body>

</html> 

 


 

Now head over to the success.html file and the following code:


<!doctype html>

<html>

  <head>

    <title>Twitter 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, head over to the main.go file and the following code:


package main

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

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

type ProviderIndex struct {
	Providers    []string
	ProvidersMap map[string]string
}

func main() {
	key := "SAgn9qi1Zt3OV8xfDaMRiBQvK"
	// maxAge := 86400 * 30 // 30 days
	// isProd := true

	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(
		twitter.New("Twitter-key", "Twitter-Secret", "http://127.0.0.1:3000/auth/twitter/callback"),
	)

	m := make(map[string]string)
	m["twitter"] = "Twitter"

	var keys []string
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	providerIndex := &ProviderIndex{
		Providers:    keys,
		ProvidersMap: m,
	}

	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("/logout/{provider}", func(res http.ResponseWriter, req *http.Request) {
		gothic.Logout(res, req)
		res.Header().Set("Location", "/")
		res.WriteHeader(http.StatusTemporaryRedirect)
	})

	p.Get("/auth/{provider}", func(res http.ResponseWriter, req *http.Request) {
		// try to get the user without re-authenticating
		if gothUser, err := gothic.CompleteUserAuth(res, req); err == nil {
			t, _ := template.ParseFiles("templates/success.html")
			t.Execute(res, gothUser)
		} else {
			gothic.BeginAuthHandler(res, req)
		}
	})

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

 

*Note: Before running the code make sure to add the go.mod file into your project directory by using the command “go mod init googleauth” and after this run, this command “go mod tidy” which will include or import all the essentials packages and libraries or GitHub that we have included in our import keyword.

 

Now your Twitter authenticaiton is ready to go. 

Run the project by using this command: “go run main.go”

And visit this site http://127.0.0.1:3000

 

Our index or login page would look like this:

 

 

By clicking on to sign in with the Twitter button we will land onto Twitter Authorize page:

 

After Authorization, we will land back on our success page with the profile information: 

GitHub: 

 

https://github.com/cosmic-weber/Golang/tree/main/Twitter_authentication_Go

  • Yaman Birla
  • 1 week
  • 45 Views

Add a comment: