OAuth

suggest change

OAuth 2.0 is the industry-standard protocol for authorization, allowing applications to access third-party resources (such as Google, GitHub, or Microsoft accounts) on behalf of a user without handling user passwords directly.

In Go, OAuth 2.0 is implemented using the official golang.org/x/oauth2 package.

Install the package:

go get golang.org/x/oauth2

Configuring the OAuth Client

Create an oauth2.Config instance specifying your client credentials, redirect URL, scopes, and authorization server endpoints:

package main

import (
	"context"
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"net/http"

	"golang.org/x/oauth2"
	"golang.org/x/oauth2/github"
)

var oauthConfig = &oauth2.Config{
	ClientID:     "YOUR_CLIENT_ID",
	ClientSecret: "YOUR_CLIENT_SECRET",
	RedirectURL:  "http://localhost:8080/callback",
	Scopes:       []string{"read:user", "user:email"},
	Endpoint:     github.Endpoint, // Pre-configured endpoint from sub-package
}

// Generate a cryptographically random state to prevent CSRF attacks
func generateState() string {
	b := make([]byte, 16)
	rand.Read(b)
	return hex.EncodeToString(b)
}

Redirecting Users to the Provider

Generate an authorization URL using AuthCodeURL and redirect the user:

func handleLogin(w http.ResponseWriter, r *http.Request) {
	state := generateState()

	// Store state in an HTTP-only session cookie to verify upon callback
	http.SetCookie(w, &http.Cookie{
		Name:     "oauth_state",
		Value:    state,
		Path:     "/",
		HttpOnly: true,
		Secure:   false, // Set to true in production with HTTPS
	})

	url := oauthConfig.AuthCodeURL(state, oauth2.AccessTypeOffline)
	http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}

Handling the Authorization Callback

When the user approves access, the provider redirects back with a code and state. Verify the state, then exchange the authorization code for an access token:

func handleCallback(w http.ResponseWriter, r *http.Request) {
	// Verify state parameter to prevent CSRF
	stateCookie, err := r.Cookie("oauth_state")
	if err != nil || r.URL.Query().Get("state") != stateCookie.Value {
		http.Error(w, "Invalid OAuth state", http.StatusBadRequest)
		return
	}

	code := r.URL.Query().Get("code")
	if code == "" {
		http.Error(w, "Missing authorization code", http.StatusBadRequest)
		return
	}

	ctx := context.Background()

	// Exchange the temporary authorization code for an OAuth2 token
	token, err := oauthConfig.Exchange(ctx, code)
	if err != nil {
		http.Error(w, fmt.Sprintf("Token exchange failed: %v", err), http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "Access Token: %s\n", token.AccessToken)
	fmt.Fprintf(w, "Token Type:   %s\n", token.TokenType)
	fmt.Fprintf(w, "Expires At:   %v\n", token.Expiry)

	// Fetch user details using authenticated client
	fetchUserProfile(ctx, token, w)
}

Making Authenticated Requests

Pass the token to oauthConfig.Client(). It returns a standard *http.Client that automatically attaches the Authorization: Bearer <token> header to all outgoing requests and automatically refreshes expired tokens if a refresh token is present:

import (
	"io"
)

func fetchUserProfile(ctx context.Context, token *oauth2.Token, w io.Writer) {
	// client handles token renewal transparently
	client := oauthConfig.Client(ctx, token)

	resp, err := client.Get("https://api.github.com/user")
	if err != nil {
		fmt.Fprintf(w, "Error fetching user: %v\n", err)
		return
	}
	defer resp.Body.Close()

	body, _ := io.ReadAll(resp.Body)
	fmt.Fprintf(w, "User Profile Response:\n%s\n", string(body))
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents