### Navigate to example directory Source: https://github.com/grokify/goauth/blob/master/ringcentral/cmd/glipbot_auth/README.md Change the working directory to the location of the glipbot_auth example. ```bash $ cd $GOPATH/src/github.com/grokify/goauth/ringcentral/examples/glipbot_auth ``` -------------------------------- ### Install GoAuth Source: https://github.com/grokify/goauth/blob/master/README.md Use this command to install the GoAuth library. Requires Go 1.24+. ```bash go get github.com/grokify/goauth ``` -------------------------------- ### Run the authentication server Source: https://github.com/grokify/goauth/blob/master/ringcentral/cmd/glipbot_auth/README.md Execute the glipbot_auth.go script to start the local HTTP server. ```bash $ go run glipbot_auth.go ``` -------------------------------- ### Install goauth library Source: https://github.com/grokify/goauth/blob/master/ringcentral/cmd/glipbot_auth/README.md Download the goauth package to your local environment. ```bash $ go get github.com/grokify/goauth ``` -------------------------------- ### Retrieve SCIM User Information Source: https://github.com/grokify/goauth/blob/master/README.md Examples for retrieving SCIM user data from various providers. ```go import "github.com/grokify/goauth/google" googleClientUtil := google.NewClientUtil(googleOAuth2HTTPClient) scimUser, err := googleClientUtil.GetSCIMUser() ``` ```go import "github.com/grokify/goauth/facebook" fbClientUtil := facebook.NewClientUtil(fbOAuth2HTTPClient) scimUser, err := fbClientUtil.GetSCIMUser() ``` ```go import "github.com/grokify/goauth/ringcentral" rcClientUtil := ringcentral.NewClientUtil(rcOAuth2HTTPClient) scimUser, err := rcClientUtil.GetSCIMUser() ``` -------------------------------- ### Make Authenticated API Requests with goapi CLI Source: https://context7.com/grokify/goauth/llms.txt Use the goapi CLI to make authenticated API requests by specifying credentials, account, and the target URL. Ensure goapi is installed via go install. ```bash go install github.com/grokify/goauth/cmd/goapi@latest goapi --creds credentials.json --account my-github-app --url https://api.github.com/user ``` -------------------------------- ### CLI Token Retrieval Tool Source: https://context7.com/grokify/goauth/llms.txt Commands for installing and using the GoAuth CLI tool to retrieve tokens. ```bash # Install the CLI tool go install github.com/grokify/goauth/cmd/goauth@latest # Get a token using credentials file goauth --creds credentials.json --account my-github-app # For authorization code flow (interactive) goauth --creds credentials.json --account my-google-app --cli ``` -------------------------------- ### Query Metabase API with Session Header Source: https://github.com/grokify/goauth/blob/master/metabase/README.md Uses the session ID obtained from authentication to authorize a GET request. ```bash curl -XGET 'https://example.com/api/database' \ -H 'X-Metabase-Session: 11112222-3333-4444-5555-666677778888' ``` -------------------------------- ### Metabase API Authentication Response Source: https://github.com/grokify/goauth/blob/master/metabase/README.md Example JSON response containing the session ID required for subsequent API calls. ```json {"id":"11112222-3333-4444-5555-666677778888"} ``` -------------------------------- ### Create HTTP Client Source: https://github.com/grokify/goauth/blob/master/README.md Initialize an HTTP client using credentials from a file. ```go package main import ( "context" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // From credentials file with account key client, err := goauth.NewClient(ctx, "credentials.json", "my-google-app") if err != nil { panic(err) } // Use client for API requests resp, err := client.Get("https://api.example.com/resource") } ``` -------------------------------- ### Configure environment variables Source: https://github.com/grokify/goauth/blob/master/ringcentral/cmd/glipbot_auth/README.md Initialize the .env file from the provided sample. ```bash $ cp sample.env .env $ vi .env ``` -------------------------------- ### Implement Basic Authentication in Go Source: https://context7.com/grokify/goauth/llms.txt Shows how to use CredentialsBasicAuth for client creation or generate a raw Basic Auth header using authutil. ```go package main import ( "fmt" "io" "log" "github.com/grokify/goauth" "github.com/grokify/goauth/authutil" ) func main() { // Using CredentialsBasicAuth struct basicCreds := goauth.CredentialsBasicAuth{ Username: "api-user", Password: "api-password", ServerURL: "https://api.example.com", AllowInsecure: false, } // Create authenticated HTTP client client, err := basicCreds.NewClient() if err != nil { log.Fatalf("Failed to create client: %v", err) } resp, err := client.Get("https://api.example.com/resource") if err != nil { log.Fatalf("Request failed: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Response: %s\n", string(body)) // Or use authutil directly for basic auth header authHeader, err := authutil.BasicAuthHeader("username", "password") if err != nil { log.Fatalf("Failed to create auth header: %v", err) } fmt.Printf("Authorization Header: %s\n", authHeader) // Output: "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" // Create client directly with authutil client2, err := authutil.NewClientBasicAuth("username", "password", false) if err != nil { log.Fatalf("Failed to create client: %v", err) } fmt.Printf("Client created: %v\n", client2 != nil) } ``` -------------------------------- ### Initialize Metabase Client in Go Source: https://github.com/grokify/goauth/blob/master/metabase/README.md Creates a new Metabase client using default environment variables for configuration. ```go import ("github.com/grokify/goauth") httpClient, authResponse, clientConfig, err := metabase.NewClientEnv(nil) ``` -------------------------------- ### Load Credentials Set Source: https://github.com/grokify/goauth/blob/master/README.md Load multiple credentials from a file and manage them as a set. ```go package main import ( "context" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // Load credentials set from file set, err := goauth.ReadFileCredentialsSet("credentials.json", true) if err != nil { panic(err) } // Get specific credentials creds, err := set.Get("my-google-app") if err != nil { panic(err) } // Create client from credentials client, err := creds.NewClient(ctx) if err != nil { panic(err) } // List all account keys accounts := set.Accounts() } ``` -------------------------------- ### Run CLI Tools Source: https://github.com/grokify/goauth/blob/master/README.md Command-line usage for token retrieval and API requests. ```bash go run cmd/goauth/main.go --credentials credentials.json --account my-app ``` ```bash go run cmd/goapi/main.go --credentials credentials.json --account my-app --url https://api.example.com/resource ``` -------------------------------- ### Retrieve SCIM User Information Source: https://context7.com/grokify/goauth/llms.txt Demonstrates how to fetch user profiles from Google, Facebook, and RingCentral using provider-specific client utilities. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth" "github.com/grokify/goauth/facebook" "github.com/grokify/goauth/google" "github.com/grokify/goauth/ringcentral" ) func main() { ctx := context.Background() // Get authenticated client (assuming credentials are configured) creds, _ := goauth.NewCredentialsFromSetFile("credentials.json", "my-google-app", false) client, _ := creds.NewClient(ctx) // Google: Get SCIM user info googleUtil := google.NewClientUtil(client) googleUser, err := googleUtil.GetSCIMUser() if err != nil { log.Printf("Failed to get Google user: %v", err) } else { fmt.Printf("Google User:\n") fmt.Printf(" Email: %s\n", googleUser.EmailAddress()) fmt.Printf(" Name: %s %s\n", googleUser.Name.GivenName, googleUser.Name.FamilyName) fmt.Printf(" Display Name: %s\n", googleUser.DisplayNameAny()) } // Facebook: Get SCIM user info fbClient, _ := goauth.NewClient(ctx, "credentials.json", "my-facebook-app") fbUtil := facebook.NewClientUtil(fbClient) fbUser, err := fbUtil.GetSCIMUser() if err != nil { log.Printf("Failed to get Facebook user: %v", err) } else { fmt.Printf("Facebook User:\n") fmt.Printf(" Email: %s\n", fbUser.EmailAddress()) fmt.Printf(" Name: %s\n", fbUser.Name.Formatted) } // RingCentral: Get SCIM user info rcClient, _ := goauth.NewClient(ctx, "credentials.json", "my-ringcentral-app") rcUtil := ringcentral.NewClientUtil(rcClient) rcUtil.ServerURL = "https://platform.ringcentral.com" rcUser, err := rcUtil.GetSCIMUser() if err != nil { log.Printf("Failed to get RingCentral user: %v", err) } else { fmt.Printf("RingCentral User:\n") fmt.Printf(" Email: %s\n", rcUser.EmailAddress()) fmt.Printf(" Phone: %s\n", rcUser.PhoneNumber()) } } ``` -------------------------------- ### Create HTTP Clients with Various Token Types in Go Source: https://context7.com/grokify/goauth/llms.txt This Go code demonstrates creating HTTP clients with different authentication schemes using goauth/authutil. It covers Bearer, Basic, OAuth2 tokens, custom authorization schemes, password credentials flow, and auth code exchange. ```go package main import ( "context" "fmt" "github.com/grokify/goauth/authutil" "golang.org/x/oauth2" ) func main() { ctx := context.Background() // Create client with Bearer token bearerClient := authutil.NewClientToken( authutil.TokenBearer, // "Bearer" "your-access-token", false, // allowInsecure ) fmt.Printf("Bearer client: %v\n", bearerClient != nil) // Create client with Basic token (base64 encoded) basicClient := authutil.NewClientTokenBase64Encode( authutil.TokenBasic, // "Basic" "username:password", false, ) fmt.Printf("Basic client: %v\n", basicClient != nil) // Create client with oauth2.Token token := &oauth2.Token{ AccessToken: "your-access-token", TokenType: "Bearer", } oauthClient := authutil.NewClientTokenOAuth2(token) fmt.Printf("OAuth client: %v\n", oauthClient != nil) // Create client with custom authorization customClient := authutil.NewClientAuthzTokenSimple("CustomScheme", "custom-token") fmt.Printf("Custom client: %v\n", customClient != nil) // Password credentials flow cfg := oauth2.Config{ ClientID: "client-id", ClientSecret: "client-secret", Endpoint: oauth2.Endpoint{ TokenURL: "https://oauth.example.com/token", }, } pwdClient, err := authutil.NewClientPasswordConf(cfg, "username", "password") if err != nil { fmt.Printf("Password client error: %v\n", err) } else { fmt.Printf("Password client: %v\n", pwdClient != nil) } // Auth code exchange authCodeClient, err := authutil.NewClientAuthCode(cfg, "authorization-code") if err != nil { fmt.Printf("Auth code client error: %v\n", err) } else { fmt.Printf("Auth code client: %v\n", authCodeClient != nil) } _ = ctx // context used in other examples } ``` -------------------------------- ### Programmatic CLI Request Handling in Go Source: https://context7.com/grokify/goauth/llms.txt This Go program demonstrates how to programmatically handle CLI-style authenticated requests using goauth.CLIRequest. It requires setting up options like credentials path and account, then executing the request to a specified URL. ```go package main import ( "context" "log" "os" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // Create CLI request handler cli := goauth.CLIRequest{ Options: goauth.Options{ CredsPath: "credentials.json", Account: "my-github-app", }, } cli.Request.Method = "GET" cli.Request.URL = "https://api.github.com/user" // Execute request and write output err := cli.Do(ctx, "", os.Stdout) if err != nil { log.Fatalf("Request failed: %v", err) } } ``` -------------------------------- ### Retrieve Pre-configured OAuth 2.0 Endpoints Source: https://context7.com/grokify/goauth/llms.txt Use the endpoints package to fetch OAuth 2.0 configuration for supported services. Some services require a subdomain parameter. ```go package main import ( "fmt" "log" "github.com/grokify/goauth/endpoints" ) func main() { // Get OAuth 2.0 endpoint for a service // Returns: oauth2.Endpoint, serverURL, error // GitHub (no subdomain required) githubEndpoint, githubServerURL, err := endpoints.NewEndpoint("github", "") if err != nil { log.Fatalf("Failed to get endpoint: %v", err) } fmt.Printf("GitHub Auth URL: %s\n", githubEndpoint.AuthURL) fmt.Printf("GitHub Token URL: %s\n", githubEndpoint.TokenURL) fmt.Printf("GitHub Server URL: %s\n", githubServerURL) // Shopify (requires subdomain) shopifyEndpoint, _, err := endpoints.NewEndpoint("shopify", "mystore") if err != nil { log.Fatalf("Failed to get endpoint: %v", err) } fmt.Printf("Shopify Auth URL: %s\n", shopifyEndpoint.AuthURL) // Output: https://mystore.myshopify.com/admin/oauth/authorize // RingCentral (production) rcEndpoint, rcServerURL, _ := endpoints.NewEndpoint("ringcentral", "") fmt.Printf("RingCentral Token URL: %s\n", rcEndpoint.TokenURL) fmt.Printf("RingCentral Server URL: %s\n", rcServerURL) // RingCentral Sandbox rcSandboxEndpoint, _, _ := endpoints.NewEndpoint("ringcentralsandbox", "") fmt.Printf("RingCentral Sandbox Token URL: %s\n", rcSandboxEndpoint.TokenURL) // Supported services: aha, asana, atlassian, ebay, ebaysandbox, facebook, // github, google, hubspot, instagram, lyft, mailchimp, monday, pagerduty, // paypal, paypalsandbox, pipedrive, ringcentral, ringcentralsandbox, // shippo, shopify, slack, stackoverflow, stripe, todoist, uber, wepay, // wepaysandbox, wrike, wunderlist, zoom } ``` -------------------------------- ### Create Authenticated HTTP Client from Credentials File Source: https://context7.com/grokify/goauth/llms.txt Use goauth.NewClient to create an authenticated http.Client by providing the context, path to the credentials JSON file, and the account key name. This is the primary method for creating clients for API requests. ```go package main import ( "context" "fmt" "io" "log" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // Create an authenticated HTTP client from credentials file // Parameters: context, credentials file path, account key name client, err := goauth.NewClient(ctx, "credentials.json", "my-github-app") if err != nil { log.Fatalf("Failed to create client: %v", err) } // Use the authenticated client to make API requests resp, err := client.Get("https://api.github.com/user") if err != nil { log.Fatalf("API request failed: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Response Status: %d\nBody: %s\n", resp.StatusCode, string(body)) } ``` -------------------------------- ### Define Basic Auth Credentials Source: https://github.com/grokify/goauth/blob/master/README.md JSON configuration for Basic authentication. ```json { "type": "basic", "basic": { "username": "your-username", "password": "your-password", "serverURL": "https://api.example.com", "allowInsecure": false } } ``` -------------------------------- ### Define Header/Query Credentials Source: https://github.com/grokify/goauth/blob/master/README.md JSON configuration for custom header and query parameter authentication. ```json { "type": "headerquery", "headerquery": { "serverURL": "https://api.example.com", "header": { "Authorization": "Bearer your-token", "X-Custom-Header": "value" }, "query": { "api_key": "your-api-key" } } } ``` -------------------------------- ### Manage Multi-Service OAuth 2.0 Source: https://context7.com/grokify/goauth/llms.txt Configures multiple OAuth providers and retrieves authenticated clients using the OAuth2Manager. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth/multiservice" "golang.org/x/oauth2" ) func main() { ctx := context.Background() // Create OAuth2 manager for multi-provider support manager := multiservice.NewOAuth2Manager() // Add Google configuration manager.ConfigSet.Add("google", multiservice.ConfigMore{ Provider: multiservice.Google, Config: oauth2.Config{ ClientID: "google-client-id", ClientSecret: "google-client-secret", RedirectURL: "https://example.com/callback", Scopes: []string{"email", "profile"}, }, }) // Add Facebook configuration manager.ConfigSet.Add("facebook", multiservice.ConfigMore{ Provider: multiservice.Facebook, Config: oauth2.Config{ ClientID: "facebook-app-id", ClientSecret: "facebook-app-secret", RedirectURL: "https://example.com/callback", Scopes: []string{"email", "public_profile"}, }, }) // Store tokens (in-memory by default, can use Redis) manager.TokenSet.SetToken("google", &oauth2.Token{ AccessToken: "user-google-access-token", }) // Get authenticated client for a specific service googleClient, err := manager.GetClient(ctx, "google") if err != nil { log.Fatalf("Failed to get Google client: %v", err) } // Get SCIM user info using the appropriate utility util, err := multiservice.NewClientUtilForProviderType(multiservice.Google) if err != nil { log.Fatalf("Failed to get client util: %v", err) } util.SetClient(googleClient) scimUser, _ := util.GetSCIMUser() fmt.Printf("User Email: %s\n", scimUser.EmailAddress()) } ``` -------------------------------- ### Configure Header and Query Parameter Authentication Source: https://context7.com/grokify/goauth/llms.txt Use CredentialsHeaderQuery to configure custom headers and query parameters for API authentication. The NewClient method creates an HTTP client that automatically includes these credentials in all requests. AllowInsecure can be set to true to bypass TLS certificate verification. ```go package main import ( "fmt" "io" "log" "net/http" "net/url" "github.com/grokify/goauth" "github.com/grokify/goauth/authutil" ) func main() { // Configure header/query authentication creds := goauth.CredentialsHeaderQuery{ ServerURL: "https://api.example.com", Header: http.Header{ "X-API-Key": []string{"your-api-key"}, "Authorization": []string{"Bearer static-token"}, }, Query: url.Values{ "api_key": []string{"your-query-api-key"}, }, AllowInsecure: false, } // Create HTTP client with auto-attached headers and query params client := creds.NewClient() // All requests will include the configured headers and query params resp, err := client.Get("https://api.example.com/resource") if err != nil { log.Fatalf("Request failed: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Response: %s\n", string(body)) // Create a simple client with base URL simpleClient := creds.NewSimpleClient() fmt.Printf("Base URL: %s\n", simpleClient.BaseURL) // Or use authutil directly client2 := authutil.NewClientHeaderQuery( http.Header{"Authorization": []string{"Bearer token"}}, url.Values{"key": []string{"value"}}, false, ) fmt.Printf("Client created: %v\n", client2 != nil) } ``` -------------------------------- ### Load and Manage Credentials Set from File Source: https://context7.com/grokify/goauth/llms.txt Utilize ReadFileCredentialsSet to load multiple credentials from a single JSON file, supporting applications that authenticate with multiple services. The endpoint inflation option can be enabled. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // Load credentials set from file with endpoint inflation set, err := goauth.ReadFileCredentialsSet("credentials.json", true) if err != nil { log.Fatalf("Failed to load credentials: %v", err) } // List all available account keys accounts := set.Accounts() fmt.Printf("Available accounts: %v\n", accounts) // Get specific credentials by key creds, err := set.Get("my-google-app") if err != nil { log.Fatalf("Failed to get credentials: %v", err) } // Create HTTP client from credentials client, err := creds.NewClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Or create client directly from set client2, err := set.NewClient(ctx, "my-ringcentral-app") if err != nil { log.Fatalf("Failed to create client: %v", err) } fmt.Printf("Created clients: %v, %v\n", client != nil, client2 != nil) } ``` -------------------------------- ### Authenticate with GCP Service Account Source: https://context7.com/grokify/goauth/llms.txt Create an authenticated HTTP client using GCP service account credentials to access Google Cloud APIs. ```go package main import ( "context" "fmt" "io" "log" "github.com/grokify/goauth" "github.com/grokify/goauth/google" ) func main() { ctx := context.Background() // Using CredentialsGCP with service account gcpCreds := goauth.CredentialsGCP{ GCPCredentials: google.Credentials{ Type: "service_account", ClientEmail: "service-account@project.iam.gserviceaccount.com", PrivateKey: "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n", PrivateKeyID: "key-id", ProjectID: "your-project-id", TokenURI: "https://oauth2.googleapis.com/token", }, Scopes: []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/spreadsheets.readonly", }, } // Create authenticated HTTP client client, err := gcpCreds.NewClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Make authenticated requests to Google APIs resp, err := client.Get("https://sheets.googleapis.com/v4/spreadsheets/SPREADSHEET_ID") if err != nil { log.Fatalf("Request failed: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Response: %s\n", string(body)) } ``` -------------------------------- ### Perform CLI-based Token Retrieval Source: https://github.com/grokify/goauth/blob/master/README.md Retrieve tokens via CLI for authorization code flow without a web server. ```go package main import ( "context" "github.com/grokify/goauth" ) func main() { ctx := context.Background() creds, _ := goauth.NewCredentialsFromSetFile("credentials.json", "my-app", false) // This will print the authorization URL and prompt for the code client, err := creds.NewClientCLI(ctx, "random-state") if err != nil { panic(err) } } ``` -------------------------------- ### Authenticate with OAuth 2.0 Password Grant in Go Source: https://context7.com/grokify/goauth/llms.txt Uses CredentialsOAuth2 to exchange resource owner credentials for an access token and create an authenticated HTTP client. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth" "github.com/grokify/goauth/authutil" "golang.org/x/oauth2" ) func main() { ctx := context.Background() // Configure password credentials flow creds := goauth.CredentialsOAuth2{ ClientID: "your-client-id", ClientSecret: "your-client-secret", Endpoint: oauth2.Endpoint{ TokenURL: "https://platform.ringcentral.com/restapi/oauth/token", }, GrantType: authutil.GrantTypePassword, Username: "+15551234567", Password: "your-password", Scopes: []string{"ReadAccount", "ReadMessages"}, } // Get token using password credentials token, err := creds.NewTokenPasswordCredentials(ctx) if err != nil { log.Fatalf("Failed to get token: %v", err) } fmt.Printf("Access Token: %s\nToken Type: %s\nExpires: %v\n", token.AccessToken, token.TokenType, token.Expiry) // Create authenticated client client, _, err := creds.NewClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } resp, _ := client.Get("https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~") fmt.Printf("Response Status: %d\n", resp.StatusCode) } ``` -------------------------------- ### Define OAuth 2.0 Credentials Source: https://github.com/grokify/goauth/blob/master/README.md JSON configuration for OAuth 2.0 authentication. ```json { "service": "github", "type": "oauth2", "oauth2": { "serverURL": "https://api.github.com", "clientID": "your-client-id", "clientSecret": "your-client-secret", "redirectURL": "https://example.com/callback", "scope": ["repo", "user"], "grantType": "authorization_code", "pkce": false } } ``` -------------------------------- ### Refresh OAuth 2.0 Tokens in Go Source: https://context7.com/grokify/goauth/llms.txt Demonstrates refreshing an expired token using an existing token object or a raw refresh token string. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth" "golang.org/x/oauth2" ) func main() { ctx := context.Background() creds := goauth.CredentialsOAuth2{ ClientID: "your-client-id", ClientSecret: "your-client-secret", Endpoint: oauth2.Endpoint{ TokenURL: "https://api.example.com/oauth/token", }, Scopes: []string{"read", "write"}, } // Existing token with refresh token existingToken := &oauth2.Token{ AccessToken: "expired-access-token", RefreshToken: "valid-refresh-token", } // Refresh the token newToken, tokenBody, err := creds.RefreshToken(ctx, existingToken) if err != nil { log.Fatalf("Failed to refresh token: %v", err) } fmt.Printf("New Access Token: %s\nRaw Response: %s\n", newToken.AccessToken, string(tokenBody)) // Or refresh using just the refresh token string newToken2, _, err := creds.RefreshTokenSimple(ctx, "your-refresh-token") if err != nil { log.Fatalf("Failed to refresh token: %v", err) } fmt.Printf("Refreshed Token: %s\n", newToken2.AccessToken) } ``` -------------------------------- ### Parse OAuth 2.0 Tokens from JSON and Readers in Go Source: https://context7.com/grokify/goauth/llms.txt This Go code shows how to parse OAuth 2.0 tokens from JSON byte slices or io.Reader interfaces using goauth/authutil. It also demonstrates creating an HTTP client directly from token JSON or a simple bearer token string. ```go package main import ( "context" "fmt" "log" "strings" "github.com/grokify/goauth/authutil" ) func main() { ctx := context.Background() // Parse token from JSON response tokenJSON := []byte(`{ "access_token": "ya29.a0AfH6SMBx...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "1//0dx..." }`) token, err := authutil.ParseToken(tokenJSON) if err != nil { log.Fatalf("Failed to parse token: %v", err) } fmt.Printf("Access Token: %s\n", token.AccessToken) fmt.Printf("Token Type: %s\n", token.TokenType) fmt.Printf("Expires: %v\n", token.Expiry) fmt.Printf("Refresh Token: %s\n", token.RefreshToken) // Create HTTP client from token JSON client, err := authutil.NewClientTokenJSON(ctx, tokenJSON) if err != nil { log.Fatalf("Failed to create client: %v", err) } fmt.Printf("Client created: %v\n", client != nil) // Create client from bearer token string or JSON tokenOrJSON := []byte("ya29.a0AfH6SMBx...") client2, err := authutil.NewClientBearerTokenSimpleOrJSON(ctx, tokenOrJSON) if err != nil { log.Fatalf("Failed to create client: %v", err) } fmt.Printf("Client from string: %v\n", client2 != nil) // Parse token from io.Reader (e.g., HTTP response body) reader := strings.NewReader(`{"access_token": "token123", "token_type": "Bearer"}`) token2, err := authutil.ParseTokenReader(reader) if err != nil { log.Fatalf("Failed to parse token: %v", err) } fmt.Printf("Parsed Token: %s\n", token2.AccessToken) } ``` -------------------------------- ### Authenticate with Metabase API via cURL Source: https://github.com/grokify/goauth/blob/master/metabase/README.md Sends a POST request with credentials to retrieve a session ID. ```bash curl -v -H "Content-Type: application/json" \ -d '{"username":"myusername","password":"mypassword"}' \ -XPOST 'http://example.com/api/session' ``` -------------------------------- ### Go OAuth 2.0 Authorization Code Flow (CLI) Source: https://context7.com/grokify/goauth/llms.txt This Go code implements the authorization code flow for CLI applications. It loads credentials from a JSON file, generates an authorization URL, and prompts the user for the authorization code to exchange for an access token. ```go package main import ( "context" "fmt" "log" "github.com/grokify/goauth" ) func main() { ctx := context.Background() // Load credentials configured for authorization_code grant creds, err := goauth.NewCredentialsFromSetFile("credentials.json", "my-google-app", false) if err != nil { log.Fatalf("Failed to load credentials: %v", err) } // Generate authorization URL and get token via CLI // This will: // 1. Print the authorization URL to visit in browser // 2. Prompt for the authorization code // 3. Exchange the code for an access token client, err := creds.NewClientCLI(ctx, "random-state-string") if err != nil { log.Fatalf("Failed to authenticate: %v", err) } // Use authenticated client resp, err := client.Get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json") if err != nil { log.Fatalf("Request failed: %v", err) } defer resp.Body.Close() fmt.Printf("Authenticated successfully! Status: %d\n", resp.StatusCode) } ``` -------------------------------- ### Define JWT Credentials Source: https://github.com/grokify/goauth/blob/master/README.md JSON configuration for JWT authentication. ```json { "type": "jwt", "jwt": { "issuer": "your-issuer", "privateKey": "your-private-key", "signingMethod": "HS256" } } ``` -------------------------------- ### Verify Salesforce credentials with curl Source: https://github.com/grokify/goauth/blob/master/salesforce/README.md Use this command to perform an OAuth 2.0 password grant request to the Salesforce token service. ```bash $ curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=myClientID" -d "client_secret=myClientSecret" -d "username=myUsername" -d "password=myPasswordMySecretToken" ``` -------------------------------- ### JSON Configuration for Multiple Credentials Source: https://github.com/grokify/goauth/blob/master/README.md This JSON structure defines multiple authentication credentials within a single configuration file. It supports various services like Google OAuth2, RingCentral password grant, and custom header/query authentication. ```json { "credentials": { "my-google-app": { "service": "google", "type": "oauth2", "oauth2": { "clientID": "your-client-id", "clientSecret": "your-client-secret", "redirectURL": "https://example.com/callback", "scope": ["email", "profile"], "grantType": "authorization_code" } }, "my-ringcentral-app": { "service": "ringcentral", "type": "oauth2", "oauth2": { "clientID": "your-client-id", "clientSecret": "your-client-secret", "grantType": "password", "username": "your-username", "password": "your-password" } }, "my-api-key": { "type": "headerquery", "headerquery": { "serverURL": "https://api.example.com", "header": { "X-API-Key": "your-api-key" } } } } } ``` -------------------------------- ### Go OAuth 2.0 Client Credentials Flow Source: https://context7.com/grokify/goauth/llms.txt Implement the client credentials grant type for server-to-server authentication without user interaction. This Go code configures credentials, obtains a token, and creates an authenticated HTTP client. ```go package main import ( "context" "fmt" "io" "log" "github.com/grokify/goauth" "github.com/grokify/goauth/authutil" "golang.org/x/oauth2" ) func main() { ctx := context.Background() // Configure OAuth 2.0 client credentials creds := goauth.CredentialsOAuth2{ ClientID: "your-client-id", ClientSecret: "your-client-secret", ServerURL: "https://api.example.com", Endpoint: oauth2.Endpoint{ TokenURL: "https://api.example.com/oauth/token", }, Scopes: []string{"read", "write"}, GrantType: authutil.GrantTypeClientCredentials, } // Get a new token token, err := creds.NewToken(ctx) if err != nil { log.Fatalf("Failed to get token: %v", err) } fmt.Printf("Access Token: %s\nExpires: %v\n", token.AccessToken, token.Expiry) // Or create an authenticated HTTP client directly client, tok, err := creds.NewClient(ctx) if err != nil { log.Fatalf("Failed to create client: %v", err) } // Make authenticated requests resp, err := client.Get("https://api.example.com/resource") if err != nil { log.Fatalf("Request failed: %v", err) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) fmt.Printf("Token Type: %s\nResponse: %s\n", tok.TokenType, string(body)) } ``` -------------------------------- ### Define OAuth2Util Interface Source: https://github.com/grokify/goauth/blob/master/README.md Interface definition for retrieving canonical user information. ```go type OAuth2Util interface { SetClient(*http.Client) GetSCIMUser() (scim.User, error) } ``` -------------------------------- ### Extract OAuth 2 parameters from URL Source: https://github.com/grokify/goauth/blob/master/docs/oauth2callback/index.html Uses URLSearchParams to retrieve and display the 'code' and 'state' parameters from the current page URL. ```javascript var params = new URLSearchParams(location.search); document.writeln('