OAuth client for Go (Golang): Connecting to OAuth 2.0 providers

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

OAuth client library for Go (Golang)



The golang.org/x/oauth2 library is the official package for working with the OAuth 2.0 protocol in Go. It provides a convenient interface for authenticating users through third-party services (Google, GitHub, Facebook, VK and others), as well as for managing access and refresh tokens.



This tool is the de facto standard for implementing OAuth 2.0 in Go applications. It is actively maintained by the Go team and used in thousands of projects, including Kubernetes, Docker and many others.



Key Features

  • Support for all OAuth 2.0 grants — Authorization Code, Client Credentials, Resource Owner Password Credentials, Implicit.
  • Automatic token management — obtaining, refreshing and storing access/refresh tokens.
  • Built-in support for popular providers — Google, GitHub, Facebook, Microsoft, Slack and others.
  • Flexible HTTP client configuration — automatic token injection into request headers.
  • Secure token storage — support for encryption and custom storage backends.
  • Integration with net/http — simple middleware for handling requests.


Installation

Installation is done via the standard go get command:

go get golang.org/x/oauth2


It is also recommended to install the package for a specific provider, for example for Google:

go get golang.org/x/oauth2/google


Basic usage example

Let's look at a simple example of authentication via Google OAuth 2.0:



package main

import ( "context" "fmt" "net/http" "golang.org/x/oauth2" "golang.org/x/oauth2/google")

func main() { // OAuth 2.0 configuration config := &oauth2.Config{ ClientID: "YOUR_CLIENT_ID", ClientSecret: "YOUR_CLIENT_SECRET", RedirectURL: "http://localhost:8080/callback", Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"}, Endpoint: google.Endpoint, }

// Create authorization URL authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) fmt.Println("Go to the link:", authURL)

// Handle callback http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { code := r.URL.Query().Get("code") token, err := config.Exchange(context.Background(), code) if err != nil { http.Error(w, "Code exchange error", http.StatusInternalServerError) return } fmt.Fprintf(w, "Access token: %s", token.AccessToken) })

http.ListenAndServe(":8080", nil)}


Working with tokens

The library provides convenient methods for working with tokens:



// Save tokentoken := &oauth2.Token{    AccessToken:  "access-token",    TokenType:    "Bearer",    RefreshToken: "refresh-token",    Expiry:       time.Now().Add(1 * time.Hour),}

// Create HTTP client with automatic token injectionclient := config.Client(context.Background(), token)

// Execute request with authorizationresp, err := client.Get("https://www.googleapis.com/oauth2/v2/userinfo")if err != nil { // handle error}defer resp.Body.Close()


Custom token storage

For production applications, it is recommended to implement a custom storage:



type TokenStorage interface {    GetToken() (*oauth2.Token, error)    SetToken(*oauth2.Token) error}

// Example using a filetype FileStorage struct { path string}

func (f *FileStorage) GetToken() (*oauth2.Token, error) { data, err := os.ReadFile(f.pat

Recommendations