Facebook Authentication with Go

Nikhil Shrestha
readytowork, Inc.
Published in
4 min readJan 7, 2024

In this article, we will walk through the process of integrating Facebook login with the Go programming language.

First, we need to set up for Facebook Developer.

Create a Facebook Developer Account:

If you don’t already have one, go to the Facebook Developer Portal, sign in with your Facebook account, and follow the steps to create a developer account.

After login, you’ll be redirected to the registration page. Choose accordingly to complete the registration process.

Create a New App:

Once logged in, go to the Facebook Developer Dashboard. Then, click on the “Create App” button.

Screen 1:

You may select according to your needs. However, you can also select “Other” if you are not sure at the moment and want to explore later.

Screen 2:

If you are not sure about the app type, you can select “None”.

Screen 3:

Enter a name for your app (here I have used the name, “Test App”). Enter your contact email. And then, click on “Create app”.

Add Facebook Login to Your App:

In the app’s dashboard, under the section “Add a Product”, click on “Set up” in the “Facebook Login” card.

Then, you’ll be redirected to next section to select your platform. However, you can skip this and select the “Settings” instead.

Configure OAuth Settings:

Here add a URL to which Facebook will redirect after a successful login. Since I am currently testing locally, I have added the URL address accordingly. Then, click on the “Save changes” button in the bottom right corner.

There are also other Facebook Login settings you can explore as per your app requirements.

Next, we can start our coding section.

Install the required packages:
You’ll need the http://golang.org/x/oauth2 package for OAuth 2.0.

Let’s set our oauthConfig variable first. This is an OAuth2 configuration with Facebook as the identity provider.

var(
oauthConfig := &oauth2.Config{
ClientID: "APP_ID",
ClientSecret: "APP_SECRET",
RedirectURL: "http://localhost:8080/callback",
Scopes: []string{"email"},
Endpoint: facebook.Endpoint,
}
)

We can get the APP_ID and APP_SECRET from our dashboard in the Facebook Developer Portal.

Go to “App settings” and inside the “Basic” section you’ll find the required keys.

Now, let’s look at our functions:

HandleHome()

func HandleHome(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<a href="/login">Login with Facebook</a>`))
}

This handler displays a link to initiate the Facebook login process.

HandleLogin()

func HandleLogin(w http.ResponseWriter, r *http.Request) {
url := oauthConfig.AuthCodeURL("state")
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

This handler generates the URL for initiating the OAuth2 flow and redirects the user to the provider’s login page, i.e., Facebook in this case.

HandleCallback()

func HandleCallback(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
oauthConfig := AuthConfig()
token, err := oauthConfig.Exchange(r.Context(), code)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

client := oauthConfig.Client(context.Background(), token)
resp, err := client.Get("https://graph.facebook.com/v13.0/me?fields=name")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer resp.Body.Close()

var userInfo struct {
Name string `json:"name"`
}

if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

fmt.Fprintf(w, "Welcome, %s!", userInfo.Name)
}

This handler retrieves the authorization code from the query parameter and exchanges it for an access token. Then, it requests the respective OAuth provider’s API using the token to fetch the name of the user. Finally, the response received from the API is decoded to get the name of the logged-in user.

main()

func main() {
http.HandleFunc("/", HandleHome)
http.HandleFunc("/login", HandleLogin)
http.HandleFunc("/callback", HandleCallback)
http.ListenAndServe(":8080", nil)
}

The main function handles the route for the different handlers.

Summary

In a nutshell, when a user visits the home route, they are provided with a link to initiate the Facebook login process. Upon clicking this link, the user is redirected to the Facebook login page, and after successful login, Facebook redirects the user back to the “/callback” route with an authorization code. The authorization code is exchanged for an access token to access the information related to the user.

--

--