githubauth

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2025 License: MIT Imports: 9 Imported by: 0

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 and installation tokens.

v2.0.0 introduces Go generics support for unified authentication with both numeric App IDs and alphanumeric Client IDs in a single, type-safe API.

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.

v2.0.0 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
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/v2

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/v2"
 "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/v2"
 "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/v2"
)

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/v2"
)

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/v2"
)

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)
}

Migration from v1.x to v2.0.0

v2.0.0 introduces breaking changes with Go generics support. Here's how to migrate:

⚠️ Breaking Changes
Removed Functions
  • NewApplicationTokenSource(int64, []byte, ...opts)
New Unified Function
  • NewApplicationTokenSource[T Identifier](T, []byte, ...opts)
🔧 Migration Guide
Before (v1.x)
// Using App ID
tokenSource1, err := githubauth.NewApplicationTokenSource(12345, privateKey)
After (v2.0.0)
import "github.com/jferrl/go-githubauth/v2"

// Using App ID - explicit int64 cast needed for type inference
tokenSource1, err := githubauth.NewApplicationTokenSource(int64(12345), privateKey)

// Using Client ID - works directly
tokenSource2, err := githubauth.NewApplicationTokenSource("Iv1.abc123", privateKey)
✨ Benefits of Migration
  • Type Safety: Compile-time verification of identifier types
  • Code Consistency: Single function for all authentication types
  • Future-Proof: Ready for potential new GitHub identifier formats
  • Enhanced Documentation: Better godoc with GitHub API references

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

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

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

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

func WithEnterpriseURLs

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