githubauth

package module
v1.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2025 License: MIT Imports: 11 Imported by: 8

README

go-githubauth

GoDoc Test Status codecov Go Report Card

go-githubauth is a Go package that provides utilities for GitHub authentication, including generating and using GitHub App tokens, installation tokens, and personal access tokens.

v1.4.0 introduces personal access token support and significant performance optimizations with intelligent token caching and high-performance HTTP clients.


Found this package useful? Give it a star on GitHub! Your support helps others discover this project and motivates continued development.

Star this repo

Share this project: Share on X Share on Reddit


Features

go-githubauth package provides implementations of the TokenSource interface from the golang.org/x/oauth2 package. This interface has a single method, Token, which returns an *oauth2.Token.

v1.4.0 Features
  • 🔐 Personal Access Token Support: Native support for both classic and fine-grained personal access tokens
  • ⚡ Advanced Token Caching: Dual-layer caching system for optimal performance
    • JWT tokens cached until expiration (up to 10 minutes)
    • Installation tokens cached until expiration (defined by GitHub response)
  • 🚀 High-Performance HTTP Client: Production-ready HTTP client with connection pooling
  • 📈 Performance Optimizations: Up to 99% reduction in unnecessary GitHub API calls
  • 🏗️ Production Ready: Optimized for high-throughput and enterprise applications
Other Features
  • 🔥 Go Generics Support: Single NewApplicationTokenSource function supports both int64 App IDs and string Client IDs
  • 🛡️ Type Safety: Compile-time verification of identifier types through generic constraints
  • ⚡ Type Inference: Automatic type detection - no need to specify generic parameters explicitly
  • 📖 Enhanced Documentation: Official GitHub API references and comprehensive JWT details
Core Capabilities
  • Generate GitHub Application JWT Generating a jwt for a github app
  • Obtain GitHub App installation tokens Authenticating as a GitHub App
  • Authenticate with Personal Access Tokens (classic and fine-grained) Managing your personal access tokens
  • RS256-signed JWTs with proper clock drift protection
  • Support for both legacy App IDs and modern Client IDs (recommended by GitHub)
  • Intelligent token caching with automatic refresh for optimal performance
  • Clean HTTP clients with connection pooling and no shared state
Requirements
  • This package is designed to be used with the golang.org/x/oauth2 package

Installation

To use go-githubauth in your project, you need to have Go installed. You can get the package via:

go get -u github.com/jferrl/go-githubauth

Usage

Usage with go-github and oauth2
package main

import (
 "context"
 "fmt"
 "os"
 "strconv"

 "github.com/google/go-github/v73/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Go automatically infers the type as string for Client ID
 appTokenSource, err := githubauth.NewApplicationTokenSource(clientID, privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 // oauth2.NewClient creates a new http.Client that adds an Authorization header with the token
 httpClient := oauth2.NewClient(context.Background(), installationTokenSource)
 githubClient := github.NewClient(httpClient)

 _, _, err = githubClient.PullRequests.CreateComment(context.Background(), "owner", "repo", 1, &github.PullRequestComment{
  Body: github.String("Awesome comment!"),
 })
 if err != nil {
  fmt.Println("Error creating comment:", err)
  return
 }
}
App ID (Legacy)
package main

import (
 "context"
 "fmt"
 "os"
 "strconv"

 "github.com/google/go-github/v73/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 appID, _ := strconv.ParseInt(os.Getenv("GITHUB_APP_ID"), 10, 64)
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Explicitly cast to int64 for App ID - Go automatically infers the type
 appTokenSource, err := githubauth.NewApplicationTokenSource(int64(appID), privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 httpClient := oauth2.NewClient(context.Background(), installationTokenSource)
 githubClient := github.NewClient(httpClient)

 _, _, err = githubClient.PullRequests.CreateComment(context.Background(), "owner", "repo", 1, &github.PullRequestComment{
  Body: github.String("Awesome comment!"),
 })
 if err != nil {
  fmt.Println("Error creating comment:", err)
  return
 }
}
Generate GitHub Application Token

First, create a GitHub App and generate a private key. To authenticate as a GitHub App, you need to generate a JWT. Generating a JWT for a GitHub App

package main

import (
 "fmt"
 "os"
 "time"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"

 // Type automatically inferred as string
 tokenSource, err := githubauth.NewApplicationTokenSource(
  clientID, 
  privateKey, 
  githubauth.WithApplicationTokenExpiration(5*time.Minute),
 )
 if err != nil {
  fmt.Println("Error creating token source:", err)
  return
 }

 token, err := tokenSource.Token()
 if err != nil {
  fmt.Println("Error generating token:", err)
  return
 }

 fmt.Println("Generated JWT token:", token.AccessToken)
}
With App ID
package main

import (
 "fmt"
 "os"
 "strconv"
 "time"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 appID, _ := strconv.ParseInt(os.Getenv("GITHUB_APP_ID"), 10, 64)

 // Type automatically inferred as int64
 tokenSource, err := githubauth.NewApplicationTokenSource(
  int64(appID), 
  privateKey, 
  githubauth.WithApplicationTokenExpiration(5*time.Minute),
 )
 if err != nil {
  fmt.Println("Error creating token source:", err)
  return
 }

 token, err := tokenSource.Token()
 if err != nil {
  fmt.Println("Error generating token:", err)
  return
 }

 fmt.Println("Generated JWT token:", token.AccessToken)
}
Generate GitHub App Installation Token

To authenticate as a GitHub App installation, you need to obtain an installation token using your GitHub App JWT.

package main

import (
 "fmt"
 "os"
 "strconv"

 "github.com/jferrl/go-githubauth"
)

func main() {
 privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))
 clientID := os.Getenv("GITHUB_APP_CLIENT_ID") // e.g., "Iv1.1234567890abcdef"
 installationID, _ := strconv.ParseInt(os.Getenv("GITHUB_INSTALLATION_ID"), 10, 64)

 // Create GitHub App JWT token source with Client ID
 appTokenSource, err := githubauth.NewApplicationTokenSource(clientID, privateKey)
 if err != nil {
  fmt.Println("Error creating application token source:", err)
  return
 }

 // Create installation token source using the app token source
 installationTokenSource := githubauth.NewInstallationTokenSource(installationID, appTokenSource)

 token, err := installationTokenSource.Token()
 if err != nil {
  fmt.Println("Error generating installation token:", err)
  return
 }

 fmt.Println("Generated installation token:", token.AccessToken)
}
Personal Access Token Authentication

GitHub Personal Access Tokens provide direct authentication for users and organizations. This package supports both classic personal access tokens and fine-grained personal access tokens.

Using Personal Access Tokens with go-github
package main

import (
 "context"
 "fmt"
 "os"

 "github.com/google/go-github/v73/github"
 "github.com/jferrl/go-githubauth"
 "golang.org/x/oauth2"
)

func main() {
 // Personal access token from environment variable
 token := os.Getenv("GITHUB_TOKEN") // e.g., "ghp_..." or "github_pat_..."

 // Create token source
 tokenSource := githubauth.NewPersonalAccessTokenSource(token)

 // Create HTTP client with OAuth2 transport
 httpClient := oauth2.NewClient(context.Background(), tokenSource)
 githubClient := github.NewClient(httpClient)

 // Use the GitHub client for API calls
 user, _, err := githubClient.Users.Get(context.Background(), "")
 if err != nil {
  fmt.Println("Error getting user:", err)
  return
 }

 fmt.Printf("Authenticated as: %s\n", user.GetLogin())
}
Creating Personal Access Tokens
  1. Classic Personal Access Token: Visit GitHub Settings > Developer settings > Personal access tokens > Tokens (classic)
  2. Fine-grained Personal Access Token: Visit GitHub Settings > Developer settings > Personal access tokens > Fine-grained tokens

Security Note: Store your personal access tokens securely and never commit them to version control. Use environment variables or secure credential management systems.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Overview

Package githubauth provides utilities for GitHub authentication, including generating and using GitHub App tokens and installation tokens.

This package implements oauth2.TokenSource interfaces for GitHub App authentication and GitHub App installation token generation. It is built on top of the go-github and golang.org/x/oauth2 libraries.

Index

Constants

View Source
const (
	// DefaultApplicationTokenExpiration is the default expiration time for GitHub App tokens.
	// The maximum allowed expiration is 10 minutes.
	DefaultApplicationTokenExpiration = 10 * time.Minute
)

Variables

This section is empty.

Functions

func NewApplicationTokenSource

func NewApplicationTokenSource[T Identifier](id T, privateKey []byte, opts ...ApplicationTokenOpt) (oauth2.TokenSource, error)

NewApplicationTokenSource creates a GitHub App JWT token source. Accepts either int64 App ID or string Client ID. GitHub recommends Client IDs for new apps. Private key must be in PEM format. Generated JWTs are RS256-signed with iat, exp, and iss claims. JWTs expire in max 10 minutes and include clock drift protection (iat set 60s in past). See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app

func NewInstallationTokenSource

func NewInstallationTokenSource(id int64, src oauth2.TokenSource, opts ...InstallationTokenSourceOpt) oauth2.TokenSource

NewInstallationTokenSource creates a GitHub App installation token source. Requires installation ID and a GitHub App JWT token source for authentication. See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-an-installation-access-token

func NewPersonalAccessTokenSource added in v1.4.0

func NewPersonalAccessTokenSource(token string) oauth2.TokenSource

NewPersonalAccessTokenSource creates a token source for GitHub personal access tokens. The provided token should be a valid GitHub personal access token (classic or fine-grained). This token source returns the same token value for all Token() calls without expiration, making it suitable for long-lived authentication scenarios.

Types

type ApplicationTokenOpt

type ApplicationTokenOpt func(*applicationTokenSource)

ApplicationTokenOpt is a functional option for configuring an applicationTokenSource.

func WithApplicationTokenExpiration

func WithApplicationTokenExpiration(exp time.Duration) ApplicationTokenOpt

WithApplicationTokenExpiration sets the JWT expiration duration. Must be between 0 and 10 minutes per GitHub's JWT requirements. Invalid values default to 10 minutes. See https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-json-web-token-jwt-for-a-github-app#about-json-web-tokens-jwts

type Identifier added in v1.3.0

type Identifier interface {
	~int64 | ~string
}

Identifier constrains GitHub App identifiers to int64 (App ID) or string (Client ID).

type InstallationTokenSourceOpt

type InstallationTokenSourceOpt func(*installationTokenSource)

InstallationTokenSourceOpt is a functional option for InstallationTokenSource.

func WithContext added in v1.1.0

WithContext sets the context for the GitHub App installation token source.

func WithEnterpriseURLs added in v1.1.0

func WithEnterpriseURLs(baseURL, uploadURL string) InstallationTokenSourceOpt

WithEnterpriseURLs sets the base URL and upload URL for GitHub Enterprise Server. This option should be used after WithHTTPClient to ensure the HTTP client is properly configured. If the provided URLs are invalid, the option is ignored and default GitHub URLs are used.

func WithHTTPClient

func WithHTTPClient(client *http.Client) InstallationTokenSourceOpt

WithHTTPClient sets the HTTP client for the GitHub App installation token source.

func WithInstallationTokenOptions

func WithInstallationTokenOptions(opts *github.InstallationTokenOptions) InstallationTokenSourceOpt

WithInstallationTokenOptions sets the options for the GitHub App installation token.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL