FusionAuth QuickStart for Go

On this page

This QuickStart explains how to add a login page and authentication to a website built with Go. You'll begin with a simple Go app that allows visitors to edit a file. Then, you'll add authentication to the app with a FusionAuth instance. Finally, you'll extend the app to handle multiple independent users with user data provided by FusionAuth.

This tutorial should take between 5 and 15 minutes; less if you already have prerequisites like Docker installed.

Prerequisites#

This QuickStart requires:

If you use macOS or Windows, you need one of the following container management tools:

  • Docker Desktop
  • OrbStack (to use OrbStack for docker compose commands after installation, run docker context use orbstack)
  • Podman (in the commands below, replace docker with podman)

Create a Simple Go App#

For this QuickStart, we'll use a Go app that reads and writes data to a text file. The app uses only the Go standard library: net/http for the web server and html/template for the page.

  1. Create a folder for the app and navigate into it:

    $ mkdir go-quickstart && cd go-quickstart
    
  2. Create a Go module named notes in the current folder:

    $ go mod init notes
    

    This creates a go.mod file, which tracks the app's dependencies.

  3. Create a file named main.go with the following code:

    package main
    
    import (
    	"html/template"
    	"log"
    	"net/http"
    	"os"
    )
    
    const notePath = "note.txt"
    
    var page = template.Must(template.ParseFiles("notes.html"))
    
    func main() {
    	http.HandleFunc("GET /{$}", showNote)
    	http.HandleFunc("POST /{$}", saveNote)
    
    	log.Println("Listening on http://localhost:3000")
    	log.Fatal(http.ListenAndServe("localhost:3000", nil))
    }
    
    func showNote(w http.ResponseWriter, r *http.Request) {
    	note, _ := os.ReadFile(notePath)
    	page.Execute(w, map[string]string{"Note": string(note)})
    }
    
    func saveNote(w http.ResponseWriter, r *http.Request) {
    	if err := os.WriteFile(notePath, []byte(r.FormValue("content")), 0o644); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, "/", http.StatusSeeOther)
    }

    showNote reads the note when the page loads, and saveNote saves it when the form is submitted.

  4. Create a file named notes.html with the following code, which displays the note in a form:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{.Note}}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
    </body>
    </html>

    The html/template package escapes the note text, so a note that contains HTML displays as text.

  5. Run the app:

    $ go run .
    
  6. Open the app at http://localhost:3000.

  7. Type "Hello Go" in the text area, then click Save Changes .

  8. In a file browser or terminal, look in the go-quickstart folder. You should see a new file named note.txt, with text content "Hello Go".

  9. Press Ctrl+C on your keyboard to stop the app.

Install and Run FusionAuth#

Before we can add authentication to our Go app, we need a local FusionAuth instance:

  1. Open your container management tool (listed in the prerequisites above).

  2. From the go-quickstart folder, clone the GitHub repository for the FusionAuth instance you'll use with this QuickStart:

    $ git clone https://github.com/FusionAuth/fusionauth-quickstart-app.git
    
  3. Navigate into the cloned directory:

    $ cd fusionauth-quickstart-app
    
  4. To start a local instance of FusionAuth, run the following command (omit the -d flag to see all Docker logs):

    $ docker compose up -d
    
  5. Wait until all networks, volumes, and containers show a green status of Healthy, Started, or Created. This may take a few minutes, depending on your network speed and cached dependencies.

  6. Open http://localhost:9011/admin to access the FusionAuth Admin UI.

  7. Log in with these credentials:

    • Login: admin@example.com
    • Password: password
  8. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the OAuth tab. On this page, you can find your client Id and client secret, and set redirect and logout URLs. In the next part of this QuickStart, we'll use these values to connect our Go app with FusionAuth.

  9. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Go app, and because FusionAuth supports SSO, we need to log out of our admin account before we can log in as a normal user.

Add FusionAuth to the Go App#

Now that you have a working instance of FusionAuth and a working Go app, let's use FusionAuth to add login to your Go app:

  1. Navigate out of the fusionauth-quickstart-app folder, back to the go-quickstart folder that contains main.go and note.txt:

    $ cd ..
    
  2. Install the dependencies we'll need to authenticate with FusionAuth:

    $ go get github.com/coreos/go-oidc/v3/oidc@v3.21.0 golang.org/x/oauth2@v0.38.0 github.com/gorilla/sessions@v1.4.0
    

    go-oidc reads FusionAuth's OpenID Connect configuration and validates the ID tokenA JSON Web Token that contains information about the authenticated user., and oauth2 builds the login URL and exchanges the authorization code for tokens. Gorilla sessions keeps the user logged in with a signed cookie, so the app doesn't need a database for sessions.

  3. Replace the contents of main.go with the following code (the client Id and client secret are the values we provided for the local FusionAuth instance, and then viewed in the Admin UI):

    package main
    
    import (
    	"context"
    	"crypto/rand"
    	"html/template"
    	"log"
    	"net/http"
    	"net/url"
    	"os"
    
    	"github.com/coreos/go-oidc/v3/oidc"
    	"github.com/gorilla/sessions"
    	"golang.org/x/oauth2"
    )
    
    const (
    	notePath      = "note.txt"
    	appURL        = "http://localhost:3000"
    	fusionAuthURL = "http://localhost:9011"
    	clientID      = "f0510a74-da7a-4101-a474-05e7f1d5ba7e"
    	clientSecret  = "super-secret-secret-that-should-be-regenerated-for-production"
    )
    
    var (
    	page = template.Must(template.ParseFiles("notes.html"))
    	// A new key on every start, so restarting the app logs everyone out.
    	store           = sessions.NewCookieStore([]byte(rand.Text()))
    	oauthConfig     *oauth2.Config
    	idTokenVerifier *oidc.IDTokenVerifier
    )
    
    func main() {
    	provider, err := oidc.NewProvider(context.Background(), fusionAuthURL)
    	if err != nil {
    		log.Fatal(err)
    	}
    	oauthConfig = &oauth2.Config{
    		ClientID:     clientID,
    		ClientSecret: clientSecret,
    		Endpoint:     provider.Endpoint(),
    		RedirectURL:  appURL + "/oauth-callback",
    		Scopes:       []string{oidc.ScopeOpenID},
    	}
    	idTokenVerifier = provider.Verifier(&oidc.Config{ClientID: clientID})
    
    	// Add Secure: true when the app runs on HTTPS.
    	store.Options = &sessions.Options{Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode}
    
    	http.HandleFunc("GET /{$}", showNote)
    	http.HandleFunc("POST /{$}", saveNote)
    	http.HandleFunc("GET /login", login)
    	http.HandleFunc("GET /oauth-callback", oauthCallback)
    	http.HandleFunc("POST /logout", logout)
    
    	log.Println("Listening on http://localhost:3000")
    	handler := http.NewCrossOriginProtection().Handler(http.DefaultServeMux)
    	log.Fatal(http.ListenAndServe("localhost:3000", handler))
    }
    
    func login(w http.ResponseWriter, r *http.Request) {
    	state := rand.Text()
    	verifier := oauth2.GenerateVerifier()
    
    	session, _ := store.Get(r, "notes")
    	session.Values["state"] = state
    	session.Values["verifier"] = verifier
    	if err := session.Save(r, w); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)), http.StatusFound)
    }
    
    func oauthCallback(w http.ResponseWriter, r *http.Request) {
    	session, _ := store.Get(r, "notes")
    	state, _ := session.Values["state"].(string)
    	verifier, _ := session.Values["verifier"].(string)
    	if state == "" || r.URL.Query().Get("state") != state {
    		http.Error(w, "Invalid login state", http.StatusBadRequest)
    		return
    	}
    
    	token, err := oauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.VerifierOption(verifier))
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    	rawIDToken, _ := token.Extra("id_token").(string)
    	idToken, err := idTokenVerifier.Verify(r.Context(), rawIDToken)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    
    	delete(session.Values, "state")
    	delete(session.Values, "verifier")
    	session.Values["userID"] = idToken.Subject
    	if err := session.Save(r, w); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, "/", http.StatusFound)
    }
    
    func logout(w http.ResponseWriter, r *http.Request) {
    	session, _ := store.Get(r, "notes")
    	session.Options.MaxAge = -1
    	session.Save(r, w)
    
    	query := url.Values{
    		"client_id":                {clientID},
    		"post_logout_redirect_uri": {appURL + "/login"},
    	}
    	http.Redirect(w, r, fusionAuthURL+"/oauth2/logout?"+query.Encode(), http.StatusSeeOther)
    }
    
    func loggedIn(r *http.Request) bool {
    	session, _ := store.Get(r, "notes")
    	_, ok := session.Values["userID"].(string)
    	return ok
    }
    
    func showNote(w http.ResponseWriter, r *http.Request) {
    	if !loggedIn(r) {
    		http.Redirect(w, r, "/login", http.StatusFound)
    		return
    	}
    	note, _ := os.ReadFile(notePath)
    	page.Execute(w, map[string]string{"Note": string(note)})
    }
    
    func saveNote(w http.ResponseWriter, r *http.Request) {
    	if !loggedIn(r) {
    		http.Redirect(w, r, "/login", http.StatusSeeOther)
    		return
    	}
    	if err := os.WriteFile(notePath, []byte(r.FormValue("content")), 0o644); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, "/", http.StatusSeeOther)
    }

    The new code connects the app to FusionAuth:

    • oidc.NewProvider finds the login and token endpoints in the OpenID Connect discovery document at /.well-known/openid-configuration.
    • sessions.NewCookieStore signs the session cookie with a random key, so users can't change the user Id stored in the cookie. The HttpOnly option hides the cookie from JavaScript in the browser. The app runs on plain HTTP, so the cookie doesn't set the Secure option.
    • The /login route sends the user to the FusionAuth login page. The route stores a random state value and a PKCEAn extension to OAuth 2.0 that mitigates authorization code interception attacks using dynamic code verifiers and challenges. code verifier in the session, and sends the code challenge to FusionAuth.
    • The /oauth-callback route checks the state value, exchanges the authorization code and code verifier for tokens, and validates the ID token. The app then stores the user's Id from the sub claim in the session.
    • The /logout route deletes the session cookie, then sends the user to FusionAuth's /oauth2/logout endpoint so the FusionAuth session ends too.
    • showNote and saveNote send users who aren't logged in to /login.
    • http.NewCrossOriginProtection rejects form submissions from other websites, which protects the app against CSRFAn attack in which a malicious site makes the user's browser send an unwanted request to a site where the user is logged in. The OAuth 2.0 state parameter protects the authorization flow from CSRF.. The middleware checks the Sec-Fetch-Site and Origin headers that browsers send, so the form doesn't need a CSRF token.
  4. Replace the contents of notes.html with the following code, which adds a Logout button:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Notes</h1>
        <form method="post" action="/">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{.Note}}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
  5. Run the app, which now uses FusionAuth login:

    $ go run .
    
  6. Open the app at http://localhost:3000. The app sends you to the FusionAuth login page.

  7. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  8. Edit and save the note in the authenticated Go app.

  9. Click Logout . FusionAuth ends your session and sends you back to the login page.

  10. Press Ctrl+C on your keyboard to stop the app.

Add Independent Notes for Each User#

To see a more realistic example of FusionAuth usage, we can improve the app even more, so every user gets a unique note to edit. To accomplish this, we'll use FusionAuth's user data:

  1. Open the FusionAuth Admin UI at http://localhost:9011/admin.

  2. Log in with the following credentials:

    • Login: admin@example.com
    • Password: password
  3. Navigate to Applications . In the QuickStart App row, click Select -> Edit , then click the Registration tab.

    • Under Self-service registration, check that Registration mode is set to Create registration. The QuickStart configuration has already turned on self-service registration.
    • In the Registration field list, turn on the Enabled and Required switches for the following rows:
      • Birthdate
      • First name
      • Last name
  4. Click Save in the top right of the page to save your changes to self-service registration.

  5. Navigate to Users . In the Richard Hendricks row, click Select -> Manage .

  6. In the Source tab, look for the firstName and lastName fields. That's what we'll use to personalize the UI for each user. We'll use the user's id field to generate a unique name for each user's note.

  7. Click the logout icon in the top right to log out of the Admin UI. We'll use a different user account to access our Go app.

  8. Replace the contents of main.go with the following code, which requests the profile scope, reads the user's name (first and last) and Id from the ID token, and stores each user's note in a separate file:

    package main
    
    import (
    	"context"
    	"crypto/rand"
    	"html/template"
    	"log"
    	"net/http"
    	"net/url"
    	"os"
    	"path/filepath"
    	"strings"
    
    	"github.com/coreos/go-oidc/v3/oidc"
    	"github.com/gorilla/sessions"
    	"golang.org/x/oauth2"
    )
    
    const (
    	dataDir       = "user_data"
    	appURL        = "http://localhost:3000"
    	fusionAuthURL = "http://localhost:9011"
    	clientID      = "f0510a74-da7a-4101-a474-05e7f1d5ba7e"
    	clientSecret  = "super-secret-secret-that-should-be-regenerated-for-production"
    )
    
    var (
    	page = template.Must(template.ParseFiles("notes.html"))
    	// A new key on every start, so restarting the app logs everyone out.
    	store           = sessions.NewCookieStore([]byte(rand.Text()))
    	oauthConfig     *oauth2.Config
    	idTokenVerifier *oidc.IDTokenVerifier
    )
    
    func main() {
    	provider, err := oidc.NewProvider(context.Background(), fusionAuthURL)
    	if err != nil {
    		log.Fatal(err)
    	}
    	oauthConfig = &oauth2.Config{
    		ClientID:     clientID,
    		ClientSecret: clientSecret,
    		Endpoint:     provider.Endpoint(),
    		RedirectURL:  appURL + "/oauth-callback",
    		Scopes:       []string{oidc.ScopeOpenID, "profile"},
    	}
    	idTokenVerifier = provider.Verifier(&oidc.Config{ClientID: clientID})
    
    	// Add Secure: true when the app runs on HTTPS.
    	store.Options = &sessions.Options{Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode}
    
    	if err := os.MkdirAll(dataDir, 0o755); err != nil {
    		log.Fatal(err)
    	}
    
    	http.HandleFunc("GET /{$}", showNote)
    	http.HandleFunc("POST /{$}", saveNote)
    	http.HandleFunc("GET /login", login)
    	http.HandleFunc("GET /oauth-callback", oauthCallback)
    	http.HandleFunc("POST /logout", logout)
    
    	log.Println("Listening on http://localhost:3000")
    	handler := http.NewCrossOriginProtection().Handler(http.DefaultServeMux)
    	log.Fatal(http.ListenAndServe("localhost:3000", handler))
    }
    
    func login(w http.ResponseWriter, r *http.Request) {
    	state := rand.Text()
    	verifier := oauth2.GenerateVerifier()
    
    	session, _ := store.Get(r, "notes")
    	session.Values["state"] = state
    	session.Values["verifier"] = verifier
    	if err := session.Save(r, w); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)), http.StatusFound)
    }
    
    func oauthCallback(w http.ResponseWriter, r *http.Request) {
    	session, _ := store.Get(r, "notes")
    	state, _ := session.Values["state"].(string)
    	verifier, _ := session.Values["verifier"].(string)
    	if state == "" || r.URL.Query().Get("state") != state {
    		http.Error(w, "Invalid login state", http.StatusBadRequest)
    		return
    	}
    
    	token, err := oauthConfig.Exchange(r.Context(), r.URL.Query().Get("code"), oauth2.VerifierOption(verifier))
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    	rawIDToken, _ := token.Extra("id_token").(string)
    	idToken, err := idTokenVerifier.Verify(r.Context(), rawIDToken)
    	if err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    	var claims struct {
    		GivenName  string `json:"given_name"`
    		FamilyName string `json:"family_name"`
    	}
    	if err := idToken.Claims(&claims); err != nil {
    		http.Error(w, err.Error(), http.StatusBadRequest)
    		return
    	}
    	name := strings.TrimSpace(claims.GivenName + " " + claims.FamilyName)
    	if name == "" {
    		name = "writer"
    	}
    
    	delete(session.Values, "state")
    	delete(session.Values, "verifier")
    	session.Values["userID"] = idToken.Subject
    	session.Values["name"] = name
    	if err := session.Save(r, w); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, "/", http.StatusFound)
    }
    
    func logout(w http.ResponseWriter, r *http.Request) {
    	session, _ := store.Get(r, "notes")
    	session.Options.MaxAge = -1
    	session.Save(r, w)
    
    	query := url.Values{
    		"client_id":                {clientID},
    		"post_logout_redirect_uri": {appURL + "/login"},
    	}
    	http.Redirect(w, r, fusionAuthURL+"/oauth2/logout?"+query.Encode(), http.StatusSeeOther)
    }
    
    func currentUser(r *http.Request) (userID, name string, ok bool) {
    	session, _ := store.Get(r, "notes")
    	userID, ok = session.Values["userID"].(string)
    	name, _ = session.Values["name"].(string)
    	return userID, name, ok
    }
    
    func notePath(userID string) string {
    	return filepath.Join(dataDir, "note-"+userID+".txt")
    }
    
    func showNote(w http.ResponseWriter, r *http.Request) {
    	userID, name, ok := currentUser(r)
    	if !ok {
    		http.Redirect(w, r, "/login", http.StatusFound)
    		return
    	}
    	note, err := os.ReadFile(notePath(userID))
    	if err != nil {
    		note = []byte("Write a note, " + name + ".")
    	}
    	page.Execute(w, map[string]string{"Name": name, "Note": string(note)})
    }
    
    func saveNote(w http.ResponseWriter, r *http.Request) {
    	userID, _, ok := currentUser(r)
    	if !ok {
    		http.Redirect(w, r, "/login", http.StatusSeeOther)
    		return
    	}
    	if err := os.WriteFile(notePath(userID), []byte(r.FormValue("content")), 0o644); err != nil {
    		http.Error(w, err.Error(), http.StatusInternalServerError)
    		return
    	}
    	http.Redirect(w, r, "/", http.StatusSeeOther)
    }

    go-oidc validated the ID token, so idToken.Claims decodes given_name and family_name without a separate JWT library. The app stores the name in the session next to the user's Id.

  9. Replace the contents of notes.html with the following code, which greets the user by name:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Notes</title>
    </head>
    <body>
        <h1>Welcome, {{.Name}}</h1>
        <form method="post" action="/">
            <label for="content">Your note</label><br>
            <textarea id="content" name="content" rows="8" cols="40">{{.Note}}</textarea><br>
            <button type="submit">Save Changes</button>
        </form>
        <form method="post" action="/logout">
            <button type="submit">Logout</button>
        </form>
    </body>
    </html>
  10. Run the app:

    $ go run .
    
  11. Open the app at http://localhost:3000.

  12. Log in with the following credentials:

    • Login: richard@example.com
    • Password: password
  13. In a separate private or incognito window, open the app at http://localhost:3000.

  14. Click Create an account and create an account using your personal email address, a password, your name, and your birthdate.

  15. Edit and save your own note. Your name appears at the top of the page and in the default note text.

Your Go app now provides unique notes for each user. Each user can independently edit and save their note. When a user saves a note, the app writes the note to a note-<id>.txt file in the user_data directory. To identify which note belongs to which user, compare the id in the file name with the id field in the user's Source tab in the Admin UI. Log out of the app before you open the Admin UI. Otherwise, FusionAuth single sign-on logs you in to the Admin UI as the app user, who doesn't have access to the Admin UI.

Summary#

In this QuickStart, FusionAuth handled login for your Go app:

  • The oauth2 and go-oidc packages sent users to the FusionAuth login page, exchanged the authorization code for tokens, and validated the ID token, so the app never saw their passwords.
  • The signed session cookie kept logged-out users away from the notes page.
  • The ID token gave the app each user's unique Id and name. The app used the Id to keep each note separate and the name to greet the user.
  • FusionAuth's self-service registration let new users create their own accounts, with no sign-up code in the app.

Next Steps#

This was a quick introduction to using FusionAuth for user authentication. To learn more about integrating FusionAuth with your product, see Get Started.

FusionAuth has many features (including Social Login, Single Sign-On, Passkeys, Multi-factor Authentication), most of which are free. This example app is a great starting point for learning about FusionAuth features.