Authentication¶
GoGitHub provides flexible authentication options for both GitHub.com and GitHub Enterprise.
REST API Client¶
Token Authentication¶
The simplest way to authenticate is with a personal access token:
import "github.com/grokify/gogithub/auth"
ctx := context.Background()
gh, err := auth.NewGitHubClient(ctx, "your-github-token")
if err != nil {
panic(err)
}
Tip
auth.NewGitHubClient() returns a raw *github.Client, coupling your code to go-github's
current major version. Prefer clientv1.NewClient() unless you specifically
need the functions on this page.
HTTP Client¶
If you need the underlying HTTP client (e.g., for custom transports):
Get Authenticated User¶
Verify authentication and get the current user:
username, err := auth.GetAuthenticatedUser(ctx, gh)
if err != nil {
// Handle authentication error
}
fmt.Printf("Authenticated as: %s\n", username)
Get User Information¶
Retrieve information about any user:
user, err := auth.GetUser(ctx, gh, "octocat")
if err != nil {
// Handle error
}
fmt.Printf("Name: %s\n", user.GetName())
Configuration¶
The config package provides a structured way to manage GitHub configuration:
From Environment Variables¶
import "github.com/grokify/gogithub/config"
cfg, err := config.FromEnv()
if err != nil {
panic(err)
}
gh, err := cfg.NewClient(ctx)
if err != nil {
panic(err)
}
Tip
cfg.NewClient() returns a raw *github.Client. Use cfg.NewClientV1() instead to get a
version-isolated clientv1.Client.
Environment Variables¶
| Variable | Description | Default |
|---|---|---|
GITHUB_TOKEN |
Personal access token | (required) |
GITHUB_OWNER |
Default repository owner | - |
GITHUB_REPO |
Default repository name | - |
GITHUB_BRANCH |
Default branch | main |
GITHUB_BASE_URL |
API base URL | https://api.github.com/ |
GITHUB_UPLOAD_URL |
Upload URL | https://uploads.github.com/ |
Manual Configuration¶
cfg := &config.Config{
Token: "your-token",
Owner: "grokify",
Repo: "gogithub",
Branch: "main",
}
if err := cfg.Validate(); err != nil {
panic(err)
}
gh, err := cfg.NewClient(ctx)
GitHub Enterprise¶
For GitHub Enterprise Server, specify custom URLs:
cfg := &config.Config{
Token: "your-token",
BaseURL: "https://github.mycompany.com/api/v3",
UploadURL: "https://github.mycompany.com/api/uploads",
}
gh, err := cfg.NewClient(ctx)
Check if a configuration is for GitHub Enterprise:
OAuth App Authentication¶
Some organizations forbid personal access tokens. A token issued to an OAuth
app is still accepted, provided the organization allows the app. The
auth/credentialsset package obtains one from a
goauth credentials set file.
Creating an OAuth App¶
- Go to GitHub Settings > Developer settings > OAuth Apps
- Click "New OAuth App"
- Set the authorization callback URL to
https://grokify.github.io/goauth/oauth2callback/(available ascredentialsset.RedirectURL). This page displays the authorization code so it can be entered on the command line. - Generate a client secret
Credentials Set File¶
{
"credentials": {
"github": {
"service": "github",
"type": "oauth2",
"oauth2": {
"clientID": "your-client-id",
"clientSecret": "your-client-secret",
"redirectURL": "https://grokify.github.io/goauth/oauth2callback/",
"scope": ["repo", "read:org"],
"grantType": "authorization_code"
}
}
}
}
This file holds a client secret. Keep it out of version control.
Creating a Client¶
import (
"os"
"github.com/grokify/gogithub/auth/credentialsset"
)
client, err := credentialsset.NewClient(ctx, "credentials.json", "github",
credentialsset.PromptReadWriter(os.Stderr, os.Stdin))
NewClient returns a clientv1.Client. The prompt prints the
authorization URL and reads the authorization code shown on the redirect
page. Confirm that the state on the redirect page matches the one printed.
To supply the code another way, pass your own AuthCodePrompt:
prompt := func(ctx context.Context, authURL, state string) (string, error) {
// Show authURL to the user and return the authorization code.
}
Reusing a Token¶
The token is not written back to the file, so each call repeats the authorization. To skip it, store the token with the account. A stored token is used as is and the prompt is not called:
"github": {
"service": "github",
"type": "oauth2",
"oauth2": { "...": "..." },
"token": { "access_token": "your-oauth-token" }
}
Use credentialsset.NewToken to obtain the token without creating a client.
Organization approval
An organization with OAuth app access restrictions must approve the app before its token can reach the organization's private resources. You can request approval on the app's authorization page.
GitHub App Authentication¶
For automated workflows and CI/CD pipelines, GitHub Apps provide better security and higher rate limits than personal access tokens.
Configuration¶
GitHub App authentication requires three pieces of information:
| Field | Description |
|---|---|
AppID |
The GitHub App's ID (found in App settings) |
InstallationID |
The installation ID for your org/repo |
PrivateKey |
The App's private key (PEM format) |
From Environment Variables¶
import "github.com/grokify/gogithub/auth"
cfg, err := auth.LoadAppConfig()
if err != nil {
panic(err)
}
gh, err := auth.NewAppClient(ctx, cfg)
if err != nil {
panic(err)
}
Environment variables:
| Variable | Description |
|---|---|
GITHUB_APP_ID |
The GitHub App ID |
GITHUB_INSTALLATION_ID |
Installation ID for target org/repo |
GITHUB_PRIVATE_KEY_PATH |
Path to private key PEM file |
GITHUB_PRIVATE_KEY |
Private key PEM content (alternative to path) |
From Config File¶
Create ~/.config/gogithub/app.json:
{
"app_id": 123456,
"installation_id": 78901234,
"private_key_path": "~/.config/gogithub/private-key.pem"
}
Then load it:
cfg, err := auth.LoadAppConfig() // Auto-discovers config file
// or
cfg, err := auth.LoadAppConfigFromFile("/path/to/app.json")
Manual Configuration¶
cfg := &auth.AppConfig{
AppID: 123456,
InstallationID: 78901234,
PrivateKey: privateKeyBytes, // PEM-encoded private key
}
gh, err := auth.NewAppClient(ctx, cfg)
List App Installations¶
To find the installation ID for your App:
installations, err := auth.ListAppInstallations(ctx, cfg)
for _, inst := range installations {
fmt.Printf("ID: %d, Account: %s (%s)\n", inst.ID, inst.Account, inst.Type)
}
Creating a GitHub App¶
- Go to Settings > Developer settings > GitHub Apps > New GitHub App
- Set the required permissions for your use case
- Generate a private key and download the PEM file
- Install the App on your organization or repositories
- Note the App ID and Installation ID from the settings
App vs Installation Tokens
GitHub Apps use short-lived installation tokens (1 hour) that are automatically created from the App's private key. This is more secure than long-lived personal access tokens.
GraphQL API Client¶
For the GraphQL API (used for contribution statistics), use a separate client:
For GitHub Enterprise:
client := graphql.NewEnterpriseClient(ctx, "your-token", "https://github.mycompany.com/api/graphql")
GraphQL Requires Authentication
Unlike the REST API which allows limited unauthenticated access, the GraphQL API always requires a token. Even for public data, you need a token (with no special scopes).
Token Scopes¶
Basic Scopes¶
| Scope | Required For |
|---|---|
| (none) | Read public data, GraphQL queries on public repos |
public_repo |
Write to public repositories |
repo |
Full access to private repositories |
read:user |
Read user profile data, contribution statistics |
read:org |
Read organization membership |
Token Requirements by Use Case¶
Public Data Only (Recommended Starting Point)¶
For reading public user statistics, contribution data, and public repository information, you need minimal permissions:
| Token Type | Configuration |
|---|---|
| Fine-grained PAT | Repository access: "Public Repositories (read-only)", no other permissions |
| Classic PAT | No scopes required (just a valid token) |
| GitHub CLI | Default gh auth login works |
This is sufficient for:
- User contribution statistics (
profile,graphqlpackages) - Public repository data (commits, releases, contributors)
- Search across public repositories
Private Repository Access¶
For accessing private repositories, you need additional permissions:
| Token Type | Configuration |
|---|---|
| Fine-grained PAT | Repository access: select specific repos, Contents: Read |
| Classic PAT | repo scope |
Write Operations¶
For creating commits, PRs, releases, etc.:
| Token Type | Configuration |
|---|---|
| Fine-grained PAT | Repository access: select repos, Contents: Read and write |
| Classic PAT | repo (private) or public_repo (public only) |
Creating a Token¶
Fine-grained tokens provide the most secure, minimal-permission approach.
For public data only:
- Go to GitHub Settings > Fine-grained tokens
- Click "Generate new token"
- Set Repository access to "Public Repositories (read-only)"
- Leave all Permissions sections empty (no permissions needed)
- Click "Generate token" and copy it
For private repository access:
- Go to GitHub Settings > Fine-grained tokens
- Click "Generate new token"
- Set Repository access to "Only select repositories" and choose your repos
- Under Repository permissions, set "Contents" to "Read-only"
- Click "Generate token" and copy it
- Go to GitHub Settings > Personal access tokens (classic)
- Click "Generate new token (classic)"
- For public data: no scopes needed
- For private repos: select
reposcope - Copy the token
Start Minimal
Start with a fine-grained token with "Public Repositories (read-only)" access and no permissions. This is sufficient for most read operations on public data. Add permissions only when needed.
Bot User Detection¶
GoGitHub provides constants for known bot users:
import "github.com/grokify/gogithub/auth"
if issue.User.GetLogin() == auth.UsernameDependabot {
fmt.Println("This is a Dependabot PR")
}
// Or check by ID
if issue.User.GetID() == auth.UserIDDependabot {
fmt.Println("This is a Dependabot PR")
}
API Reference¶
See pkg.go.dev/github.com/grokify/gogithub/auth for complete API documentation.