Documentation
¶
Overview ¶
Package gitlaboauth2 provides OAuth2 configuration utilities for GitLab API clients.
This package simplifies the creation of OAuth2 configurations for both GitLab.com and self-managed GitLab instances. It handles the proper endpoint configuration automatically based on the provided base URL.
Example usage for GitLab.com:
config := gitlaboauth2.NewOAuth2Config("", "your-client-id", []string{"read_user", "read_repository"})
Example usage for self-managed GitLab:
config := gitlaboauth2.NewOAuth2Config("https://gitlab.example.com", "your-client-id", []string{"read_user"})
The package automatically configures the appropriate OAuth2 endpoints and uses a default redirect URI suitable for local development.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AuthorizationFlow ¶
func AuthorizationFlow(ctx context.Context, baseURL, clientID, redirectURL string, scopes []string, callbackServerListenAddr string, browser BrowserFunc) (*oauth2.Token, error)
AuthorizationFlow performs a complete OAuth2 authorization flow for GitLab authentication.
This function provides a simplified interface for performing OAuth2 authentication by combining the OAuth2 configuration creation and callback server handling into a single convenient function call.
The function: 1. Creates an OAuth2 configuration for the specified GitLab instance 2. Sets up a local callback server on port 7171 3. Opens the authorization URL in the user's browser 4. Waits for the user to complete authentication 5. Handles the callback and exchanges the code for an access token 6. Returns the access token
Parameters:
- ctx: Context for cancellation and timeout control
- baseURL: The base URL of the GitLab instance. Use "" for GitLab.com, or provide the full URL for self-managed instances (e.g., "https://gitlab.example.com")
- clientID: The OAuth2 client ID obtained from your GitLab application settings
- scopes: A slice of OAuth2 scopes to request (e.g., []string{"read_user", "api"})
- browser: A function that opens URLs in the user's browser
Returns:
- *oauth2.Token: The OAuth2 access token on successful authentication
- error: An error if the authentication flow fails at any step
This function is a convenience wrapper around NewOAuth2Config and NewCallbackServer. For more control over the authentication flow, use those functions directly.
Example usage for GitLab.com:
browserFunc := func(url string) error { return exec.Command("open", url).Start() // macOS } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() token, err := gitlaboauth2.AuthorizationFlow(ctx, "", "your-client-id", "http://localhost:7171/auth/redirect", []string{"read_user", "api"}, ":7171", browserFunc) if err != nil { log.Fatalf("Authentication failed: %v", err) } fmt.Printf("Access token: %s\n", token.AccessToken)
Example usage for self-managed GitLab:
browserFunc := func(url string) error { return exec.Command("xdg-open", url).Start() // Linux } ctx := context.Background() token, err := gitlaboauth2.AuthorizationFlow(ctx, "https://gitlab.company.com", "your-client-id", "http://localhost:7171/auth/redirect", []string{"read_user"}, ":7171", browserFunc) if err != nil { log.Fatalf("Authentication failed: %v", err) } // Use the token to create an authenticated HTTP client config := gitlaboauth2.NewOAuth2Config("https://gitlab.company.com", "your-client-id", []string{"read_user"}) client := config.Client(ctx, token) // Now you can use the client to make authenticated requests resp, err := client.Get("https://gitlab.company.com/api/v4/user") if err != nil { log.Fatalf("API request failed: %v", err) } defer resp.Body.Close()
func NewOAuth2Config ¶
NewOAuth2Config creates a new OAuth2 configuration for GitLab authentication.
This function configures OAuth2 settings for both GitLab.com and self-managed GitLab instances. It automatically determines the appropriate OAuth2 endpoints based on the provided base URL.
Parameters:
- baseURL: The base URL of the GitLab instance. Use an empty string "" for GitLab.com. For self-managed instances, provide the full URL (e.g., "https://gitlab.example.com"). The function automatically handles URL normalization by removing trailing slashes and "/api/v4" suffixes.
- clientID: The OAuth2 client ID obtained from your GitLab application settings.
- scopes: A slice of OAuth2 scopes to request. Common scopes include: "read_user", "read_repository", "write_repository", "api", "read_api", etc.
Returns:
- *oauth2.Config: A configured OAuth2 configuration ready for use with the golang.org/x/oauth2 package.
The function automatically sets a default redirect URI suitable for local development (http://localhost:7171/auth/redirect).
Example usage for GitLab.com:
config := gitlaboauth2.NewOAuth2Config("", "your-client-id", []string{"read_user", "api"}) authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
Example usage for self-managed GitLab:
config := gitlaboauth2.NewOAuth2Config("https://gitlab.company.com", "your-client-id", []string{"read_user"}) authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline) // Later, exchange the authorization code for a token token, err := config.Exchange(context.Background(), "authorization-code") if err != nil { log.Fatal(err) } // Create an HTTP client with the token client := config.Client(context.Background(), token)
Types ¶
type BrowserFunc ¶
BrowserFunc is a function type for opening URLs in a browser.
This function should open the provided URL in the user's default browser or handle the URL opening in an appropriate way for the application.
Parameters:
- url: The authorization URL to open in the browser
Returns:
- error: An error if the browser could not be opened, nil otherwise
Example implementation using the "xdg-open" command:
browserFunc := func(url string) error { return exec.Command("xdg-open", url).Start() }
type CallbackServer ¶
type CallbackServer struct {
// contains filtered or unexported fields
}
CallbackServer handles the OAuth2 callback flow for GitLab authentication.
This server provides a complete OAuth2 flow implementation that: - Starts a local HTTP server to handle the OAuth2 callback - Opens the authorization URL in the user's browser - Handles the callback with the authorization code - Exchanges the code for an access token - Automatically shuts down after completion
The server uses PKCE (Proof Key for Code Exchange) for enhanced security and handles state verification to prevent CSRF attacks.
func NewCallbackServer ¶
func NewCallbackServer(config *oauth2.Config, addr string, browser BrowserFunc) *CallbackServer
NewCallbackServer creates a new callback server for handling OAuth2 authentication flow.
This function initializes a CallbackServer that manages the complete OAuth2 flow, including starting a local HTTP server, opening the browser, and handling the callback.
Parameters:
- config: The OAuth2 configuration created with NewOAuth2Config
- addr: The address for the local HTTP server (e.g., ":7171" or "localhost:8080")
- browser: A function that opens URLs in the user's browser
Returns:
- *CallbackServer: A configured callback server ready to handle OAuth2 flow
Example usage:
config := gitlaboauth2.NewOAuth2Config("", "client-id", []string{"read_user"}) browserFunc := func(url string) error { return exec.Command("open", url).Start() // macOS } server := gitlaboauth2.NewCallbackServer(config, ":7171", browserFunc) ctx := context.Background() token, err := server.GetToken(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Access token: %s\n", token.AccessToken)
func (*CallbackServer) GetToken ¶
GetToken performs the complete OAuth2 flow and returns an access token.
This method orchestrates the entire OAuth2 authentication flow by: 1. Generating a secure state and PKCE verifier for security 2. Starting a local HTTP server to handle the callback 3. Opening the authorization URL in the user's browser 4. Waiting for the user to complete authentication 5. Handling the callback with the authorization code 6. Exchanging the code for an access token 7. Automatically shutting down the server
The method uses PKCE (Proof Key for Code Exchange) for enhanced security and implements proper state verification to prevent CSRF attacks.
Parameters:
- ctx: Context for cancellation and timeout control
Returns:
- *oauth2.Token: The OAuth2 access token on successful authentication
- error: An error if the authentication flow fails at any step
The method will block until: - The user completes authentication and a token is obtained - The context is canceled or times out - An error occurs during the authentication process
Example usage:
config := gitlaboauth2.NewOAuth2Config("", "client-id", []string{"read_user"}) browserFunc := func(url string) error { return exec.Command("open", url).Start() } server := gitlaboauth2.NewCallbackServer(config, ":7171", browserFunc) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) defer cancel() token, err := server.GetToken(ctx) if err != nil { log.Fatalf("Authentication failed: %v", err) } fmt.Printf("Access token: %s\n", token.AccessToken) fmt.Printf("Token type: %s\n", token.TokenType) fmt.Printf("Expires at: %v\n", token.Expiry)