### Setup Command Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/03-cli-reference.md
Use this command to test OIDC provider configuration and view token claims without modifying kubeconfig.
```bash
kubectl oidc-login setup \
--oidc-issuer-url=https://accounts.google.com \
--oidc-client-id=YOUR_CLIENT_ID.apps.googleusercontent.com
```
--------------------------------
### GetDeviceAuthorization Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example demonstrating how to initiate the device authorization flow and display the user code and verification URL.
```go
authResp, err := oidcClient.GetDeviceAuthorization(ctx)
if err != nil {
// Handle device flow error
}
fmt.Printf("Enter code %s at %s\n", authResp.UserCode, authResp.VerificationURL)
```
--------------------------------
### Display Kubelogin Setup Help
Source: https://github.com/int128/kubelogin/blob/master/docs/setup.md
Use this command to view all available options and flags for the `kubectl oidc-login setup` command.
```sh
kubectl oidc-login setup --help
```
--------------------------------
### GetTokenByROPC Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example demonstrating how to use the GetTokenByROPC function to obtain tokens using a username and password.
```go
tokenSet, err := oidcClient.GetTokenByROPC(ctx, "user@example.com", "password123")
if err != nil {
// Handle password flow error
}
```
--------------------------------
### GetTokenByClientCredentials Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example demonstrating how to use the GetTokenByClientCredentials function, including specifying additional endpoint parameters like 'audience'.
```go
tokenSet, err := oidcClient.GetTokenByClientCredentials(ctx, client.GetTokenByClientCredentialsInput{
EndpointParams: map[string][]string{
"audience": {"https://api.example.com"},
},
})
```
--------------------------------
### Check Token Expiration with Setup Command
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Uses the 'setup' command to display decoded token claims, including the expiration time ('exp'). This is useful for verifying token validity.
```bash
# Setup command shows token details including expiration
kubectl oidc-login setup \
--oidc-issuer-url=https://accounts.google.com \
--oidc-client-id=YOUR_CLIENT_ID
# Displays decoded token claims:
# {
# "sub": "user123",
# "exp": 1735689600,
# "aud": "YOUR_CLIENT_ID",
# "iss": "https://accounts.google.com"
# }
```
--------------------------------
### Client Credentials Flow Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Demonstrates how to initiate the Client Credentials flow to obtain an access token for service-to-service authentication.
```go
clientCreds := &clientcredentials.ClientCredentials{
Logger: logger,
}
input := &client.GetTokenByClientCredentialsInput{
EndpointParams: map[string][]string{
"audience": {"https://api.example.com"},
},
}
tokenSet, err := clientCreds.Do(ctx, input, oidcClient)
```
--------------------------------
### Example: Load OIDC Configuration by User
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Shows an example of using the LoadByUser method to fetch OIDC authentication provider details for a given user from a kubeconfig file. Verify the kubeconfig path and user name.
```go
authProvider, err := loader.LoadByUser(
context.Background(),
filepath.Join(os.Getenv("HOME"), ".kube/config"),
kubeconfig.UserName("oidc-user"),
)
if err != nil {
return err
}
```
--------------------------------
### GitHub Actions CI/CD Integration for Kubelogin
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Automate OIDC authentication in a GitHub Actions workflow. This example installs kubelogin, configures the kubeconfig using secrets, and then performs the authentication using client credentials.
```yaml
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Configure kubeconfig
run: |
mkdir -p ~/.kube
echo "${{ secrets.KUBECONFIG }}" | base64 -d > ~/.kube/config
- name: Install kubelogin
run: |
curl -L -o kubelogin.tar.gz https://github.com/int128/kubelogin/releases/download/v1.31.0/kubelogin_linux_amd64.tar.gz
tar -xzf kubelogin.tar.gz
sudo mv kubectl-oidc_login /usr/local/bin/
- name: Authenticate with OIDC
run: |
kubectl oidc-login get-token \
--oidc-issuer-url=${{ secrets.OIDC_ISSUER }} \
--oidc-client-id=${{ secrets.OIDC_CLIENT_ID }} \
--oidc-client-secret=${{ secrets.OIDC_CLIENT_SECRET }} \
--grant-type=client-credentials \
--token-cache-storage=none
- name: Deploy
run: kubectl apply -f manifests/
```
--------------------------------
### Initiate Resource Owner Password Credentials (ROPC) Flow
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Executes the ROPC flow by exchanging username and password directly for an access token. This example shows basic setup and error handling for invalid credentials.
```go
ropc := &ropc.ROPC{
Logger: logger,
}
option := &ropc.Option{
Username: "user@example.com",
Password: "password123",
}
tokenSet, err := ropc.Do(ctx, option, oidcClient)
if err != nil {
log.Printf("Authentication failed: %v", err)
// Likely invalid credentials
}
```
--------------------------------
### ExchangeDeviceCode Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example demonstrating how to use the ExchangeDeviceCode function to poll for token exchange after initiating the device authorization flow.
```go
tokenSet, err := oidcClient.ExchangeDeviceCode(ctx, authResp)
if err != nil {
// Handle timeout or denial
}
```
--------------------------------
### GetTokenByAuthCode Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example demonstrating how to use the GetTokenByAuthCode function, including setting up a channel to open the authorization URL in a browser.
```go
readyChan := make(chan string, 1)
go func() {
if url, ok := <-readyChan; ok {
browser.Open(url)
}
}()
tokenSet, err := oidcClient.GetTokenByAuthCode(ctx, client.GetTokenByAuthCodeInput{
BindAddress: []string{"127.0.0.1:8000", "127.0.0.1:18000"},
State: state,
Nonce: nonce,
PKCEParams: pkceParams,
LocalServerSuccessHTML: "
Success",
}, readyChan)
```
--------------------------------
### Version Command Output Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/03-cli-reference.md
This shows the expected output format when querying the version of the kubelogin CLI.
```text
kubelogin version (go1.26.3 linux_amd64)
```
--------------------------------
### Example Usage of ContextName
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Demonstrates how to create an instance of ContextName. This is a basic type conversion for string literals.
```go
contextName := kubeconfig.ContextName("my-cluster-context")
```
--------------------------------
### Install kubelogin via Chocolatey
Source: https://github.com/int128/kubelogin/blob/master/README.md
For Windows users, install kubelogin using the Chocolatey package manager.
```sh
choco install kubelogin
```
--------------------------------
### Browser Open Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Opens a given URL in the default system browser. Handles potential errors during browser launch and suggests fallback mechanisms.
```go
browser := &browser.Browser{}
ctx := context.Background()
err := browser.Open(ctx, "https://accounts.google.com/o/oauth2/v2/auth?...")
if err != nil {
log.Printf("Could not open browser: %v", err)
// Fallback to keyboard entry
}
```
--------------------------------
### Command Providers
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Provides the main CLI command interface and its subcommands (Root, GetToken, Setup, Clean).
```go
// CLI Commands
cmd.Set
├── cmd.Interface (Cmd)
├── cmd.Root
├── cmd.GetToken
├── cmd.Setup
└── cmd.Clean
```
--------------------------------
### Get Token Command Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/03-cli-reference.md
Use this command to retrieve or refresh an OIDC token. Ensure all required provider configuration flags are set.
```bash
kubectl oidc-login get-token \
--oidc-issuer-url=https://accounts.google.com \
--oidc-client-id=YOUR_CLIENT_ID.apps.googleusercontent.com \
--oidc-client-secret=YOUR_CLIENT_SECRET \
--token-cache-storage=keyring
```
--------------------------------
### Install kubelogin via Krew
Source: https://github.com/int128/kubelogin/blob/master/README.md
Install kubelogin using Krew, the Kubernetes plugin manager, which supports macOS, Linux, and Windows, including ARM architectures.
```sh
kubectl krew install oidc-login
```
--------------------------------
### Example Usage of UserName
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Shows how to instantiate a UserName type. This is a simple type conversion from a string literal.
```go
userName := kubeconfig.UserName("oidc-user")
```
--------------------------------
### Real Clock Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Provides the current system time using `time.Now()`. This is the default implementation for production environments.
```go
clock := &clock.Real{}
if claims.IsExpired(clock) {
// Token has expired
}
```
--------------------------------
### Set up Kubelogin Configuration
Source: https://github.com/int128/kubelogin/blob/master/docs/setup.md
Run this command to initiate the Kubelogin setup process and display configuration instructions. Ensure you replace placeholders with your OIDC provider's details.
```sh
kubectl oidc-login setup --oidc-issuer-url=ISSUER_URL --oidc-client-id=YOUR_CLIENT_ID
```
--------------------------------
### Create OIDC Client Instance
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Example of creating a new OIDC client using the factory. Ensure the provider details and TLS configuration are correctly set.
```go
factory := &client.Factory{
Loader: tlsclientconfigLoader,
Clock: clock,
Logger: logger,
}
ctx := context.Background()
oidcClient, err := factory.New(ctx, oidc.Provider{
IssuerURL: "https://accounts.google.com",
ClientID: "YOUR_CLIENT_ID.apps.googleusercontent.com",
ClientSecret: "YOUR_SECRET",
}, tlsclientconfig.Config{})
if err != nil {
// Handle OIDC discovery error
}
```
--------------------------------
### Use Kubelogin as a Library in Custom Applications
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/00-index.md
Integrate kubelogin into custom applications by using its internal APIs. This example shows how to initialize the command and run it with specific arguments.
```go
import "github.com/int128/kubelogin/pkg/di"
cmd := di.NewCmd()
exitCode := cmd.Run(ctx, []string{"kubelogin", "get-token", ...}, "v1.31.0")
```
--------------------------------
### Install kubelogin via Homebrew
Source: https://github.com/int128/kubelogin/blob/master/README.md
Use this command to install the latest version of kubelogin on macOS and Linux systems using Homebrew.
```sh
brew install kubelogin
```
--------------------------------
### Example: Executing an Authentication Flow
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Demonstrates how to instantiate the `Authentication` struct and call its `Do` method with a browser-based authorization code flow configuration. Ensure all necessary dependencies like `clientFactory`, `logger`, and specific flow handlers are provided.
```go
auth := &authentication.Authentication{
ClientFactory: clientFactory,
Logger: logger,
AuthCodeBrowser: authCodeBrowser,
AuthCodeKeyboard: authCodeKeyboard,
ROPC: ropcAuth,
DeviceCode: deviceCodeAuth,
ClientCredentials: clientCredsAuth,
}
input := authentication.Input{
Provider: oidc.Provider{
IssuerURL: "https://accounts.google.com",
ClientID: "YOUR_CLIENT_ID.apps.googleusercontent.com",
ClientSecret: "YOUR_SECRET",
},
GrantOptionSet: authentication.GrantOptionSet{
AuthCodeBrowserOption: &authcode.BrowserOption{
BindAddress: []string{"127.0.0.1:8000"},
AuthenticationTimeout: 180 * time.Second,
},
},
TLSClientConfig: tlsclientconfig.Config{},
}
output, err := auth.Do(ctx, input)
if err != nil {
log.Printf("Authentication failed: %v", err)
return err
}
fmt.Printf("Authenticated as: %s\n", output.TokenSet.IDToken)
```
--------------------------------
### Build Kubelogin Plugin
Source: https://github.com/int128/kubelogin/blob/master/acceptance_test/README.md
Build the kubelogin plugin into the parent directory. Ensure Docker, Kind, and kubectl are installed.
```sh
make -C ..
```
--------------------------------
### Verbose Logging Example with kubectl
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Illustrates how to enable verbose logging for authentication flows using the kubectl oidc-login command with the -v1 flag.
```bash
kubectl oidc-login get-token -v1 \
--oidc-issuer-url=https://accounts.google.com \
--oidc-client-id=YOUR_CLIENT_ID
```
--------------------------------
### Composite Provider Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Build complex providers by composing simpler ones. Wire automatically determines the correct order of dependency resolution.
```go
// Simple providers
func ProvideClock() clock.Interface {
return &clock.Real{}
}
func ProvideLogger() logger.Interface {
return &logger.StdoutLogger{}
}
// Composite provider (depends on simpler providers)
func ProvideOIDCClient(
logger logger.Interface,
clock clock.Interface,
) oidc.Client {
return &oidc.ClientImpl{Logger: logger, Clock: clock}
}
```
--------------------------------
### JWT Standard Format Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
A typical JWT token follows the structure: header.payload.signature. This example shows the complete token.
```text
eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNzA5MjU5MjAwfQ.signature_here
```
--------------------------------
### Stdio Stdout Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Returns a writer for standard output, commonly used for outputting structured data like JSON for credential plugins.
```go
stdio := &stdio.Stdio{}
out := stdio.Stdout()
json.NewEncoder(out).Encode(credentialPluginOutput)
```
--------------------------------
### Struct Field Auto-wiring Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Demonstrates how Wire uses struct tags to automatically inject dependencies based on type matching.
```go
type GetToken struct {
GetToken credentialplugin.Interface // auto-wired
Logger logger.Interface // auto-wired
}
```
--------------------------------
### Clean Token Cache via CLI
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/06-token-cache-api.md
Command-line examples for cleaning the token cache, useful for logging out, switching providers, or debugging.
```bash
# User log out
kubectl oidc-login clean --token-cache-dir=~/.kube/cache/oidc-login
# User switches providers
kubectl oidc-login clean --token-cache-storage=keyring
# Debugging: confirm cache is empty before re-auth
ls -la ~/.kube/cache/oidc-login/
```
--------------------------------
### Kubernetes RBAC Role Binding Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Example of a Kubernetes ClusterRoleBinding that maps an OIDC user to a specific Kubernetes role (e.g., 'view'). This demonstrates how RBAC applies after Kubelogin obtains a token.
```yaml
# Role Binding: Map OIDC user to Kubernetes role
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: oidc-users
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: view
subjects:
- kind: User
name: user@example.com # From OIDC 'sub' claim
apiGroup: rbac.authorization.k8s.io
```
--------------------------------
### Logger Verbosity Configuration Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Examples of setting logger verbosity using the -v flag. Higher verbosity levels provide more detailed internal information.
```bash
kubectl oidc-login get-token -v1 --oidc-issuer-url=...
kubectl oidc-login setup -v2 --oidc-client-id=...
```
--------------------------------
### Setup OIDC Provider Authentication
Source: https://github.com/int128/kubelogin/blob/master/pkg/cmd/setup.md
Run this command to authenticate with your OpenID Connect Provider. Ensure you replace ISSUER_URL and YOUR_CLIENT_ID with your specific provider details.
```bash
kubectl oidc-login setup \
--oidc-issuer-url=ISSUER_URL \
--oidc-client-id=YOUR_CLIENT_ID
```
--------------------------------
### Kubectl Credential Plugin Configuration
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/00-index.md
Example YAML configuration for integrating Kubelogin as a credential plugin with kubectl.
```yaml
users:
- name: oidc-user
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: kubectl
args:
- oidc-login
- get-token
- --oidc-issuer-url=https://accounts.google.com
- --oidc-client-id=YOUR_CLIENT_ID
- --oidc-client-secret=YOUR_SECRET
```
--------------------------------
### Example: Load OIDC Configuration by Context
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Demonstrates how to use the LoadByContext method to retrieve OIDC authentication provider details from a kubeconfig file. Ensure the kubeconfig path and context name are correct.
```go
loader := &kubeconfig_loader.Loader{}
authProvider, err := loader.LoadByContext(
context.Background(),
filepath.Join(os.Getenv("HOME"), ".kube/config"),
kubeconfig.ContextName("my-cluster"),
)
if err != nil {
log.Printf("Failed to load kubeconfig: %v", err)
return err
}
fmt.Printf("IDP Issuer: %s\n", authProvider.IDPIssuerURL)
fmt.Printf("Client ID: %s\n", authProvider.ClientID)
```
--------------------------------
### Device Authorization Flow Setup
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Initiates the device authorization flow for systems with limited I/O, like IoT devices. It provides a code and URL for the user to authorize on another device.
```bash
# On device with limited I/O
cubelogin setup \
--oidc-issuer-url=https://auth.example.com \
--oidc-client-id=device-123 \
--grant-type=device-code
# Output:
# Enter code ABC123 at https://auth.example.com/device
# Waiting for authorization...
# User opens URL on phone or browser:
# - Enters device code
# - Approves device access
# Device completes authentication
```
--------------------------------
### Logger Printf Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Prints a user-facing message or error to stderr. Use for general output that should always be visible.
```go
logger.Printf("OIDC token valid until %s", claims.Expiry)
```
--------------------------------
### Reader ReadString Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Prompts the user with a message and reads a single line of input from stdin. Returns the input string or an error if reading fails.
```go
reader := &reader.Reader{}
code, err := reader.ReadString("Enter authorization code: ")
if err != nil {
return err
}
// Exchange code for token
```
--------------------------------
### Use Case Providers
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Organizes providers for various use cases including Authentication, Credential Plugin, Setup, and Clean, each with its own wire Set.
```go
// Authentication use case
authentication.Set
├── authentication.Interface
└── Sub-flows (AuthCodeBrowser, AuthCodeKeyboard, ROPC, etc.)
// Credential Plugin use case
credentialplugin.Set
├── credentialplugin.Interface
├── credentialplugin_reader.Interface
└── credentialplugin_writer.Interface
// Setup use case
setup.Set
└── setup.Interface
// Clean use case
clean.Set
└── clean.Interface
```
--------------------------------
### Kubeconfig Integration Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/04-credential-plugin-api.md
This YAML configuration shows how to integrate the Kubelogin credential plugin into a Kubernetes kubeconfig file, specifying OIDC provider details and cache settings.
```yaml
apiVersion: v1
kind: Config
clusters:
- cluster:
server: https://api.example.com
name: example-cluster
users:
- name: example-oidc
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: kubectl
args:
- oidc-login
- get-token
- --oidc-issuer-url=https://accounts.google.com
- --oidc-client-id=YOUR_CLIENT_ID.apps.googleusercontent.com
- --oidc-client-secret=YOUR_CLIENT_SECRET
- --token-cache-dir=~/.kube/cache/oidc-login
- --token-cache-storage=keyring
contexts:
- context:
cluster: example-cluster
user: example-oidc
name: example-context
current-context: example-context
```
--------------------------------
### Logger V(level).Infof Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Logs debug information at a specified verbosity level. Output is conditional on the verbosity setting.
```go
logger.V(1).Infof("token cache hit for provider %s", provider.IssuerURL)
logger.V(2).Infof("discovered PKCE methods: %v", methods)
```
--------------------------------
### Get Token with Client Credentials Grant (CI/CD)
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/00-index.md
Use client credentials grant in automated environments like CI/CD pipelines. Set token-cache-storage to none to avoid storing tokens.
```bash
kubectl oidc-login get-token \
--oidc-issuer-url=$OIDC_ISSUER \
--oidc-client-id=$OIDC_CLIENT_ID \
--oidc-client-secret=$OIDC_CLIENT_SECRET \
--grant-type=client-credentials \
--token-cache-storage=none
```
--------------------------------
### Kubelogin Module Dependencies
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/00-index.md
Illustrates the dependency flow between different modules within the kubelogin project, starting from CLI commands down to shared infrastructure.
```text
CLI Commands (cmd)
↓
Use Cases (usecases)
├→ Authentication (oidc/client)
├→ Token Cache (tokencache/repository)
└→ Kubeconfig I/O (kubeconfig)
↓
Shared Infrastructure
├→ Logger
├→ Browser
├→ Reader
└→ Clock
```
--------------------------------
### Root Command Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/03-cli-reference.md
Use the root command to update kubeconfig user credentials for standalone mode. Specify kubeconfig and user if not default.
```bash
kubectl oidc-login --kubeconfig=~/.kube/config --user=oidc-user
```
--------------------------------
### Token Refresh Attempt Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Shows how Kubelogin attempts to refresh an existing token if a valid refresh token is available before performing a full authentication.
```go
if in.CachedTokenSet != nil && in.CachedTokenSet.RefreshToken != "" {
u.Logger.V(1).Infof("refreshing the token")
tokenSet, err := oidcClient.Refresh(ctx, in.CachedTokenSet.RefreshToken)
if err == nil {
return &Output{TokenSet: *tokenSet}, nil
}
u.Logger.V(1).Infof("could not refresh the token: %s", err)
// Fall through to perform full authentication
}
```
--------------------------------
### Initiate Browser Authorization Code Flow
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Executes the interactive browser-based OAuth2 authorization code flow. This example demonstrates setting custom bind addresses, a longer authentication timeout, and a specific browser command.
```go
browser := &authcode.Browser{
Browser: &browser.Browser{},
Logger: logger,
}
option := &authcode.BrowserOption{
BindAddress: []string{"127.0.0.1:8000", "127.0.0.1:18000"},
AuthenticationTimeout: 5 * time.Minute,
SkipOpenBrowser: false,
BrowserCommand: "firefox %s", // Custom browser
}
tokenSet, err := browser.Do(ctx, option, oidcClient)
```
--------------------------------
### Example kubeconfig for OIDC authentication
Source: https://github.com/int128/kubelogin/blob/master/README.md
Configure your kubeconfig file to use kubelogin for OIDC authentication. Replace ISSUER_URL and YOUR_CLIENT_ID with your specific OIDC provider details.
```yaml
users:
- name: oidc
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: kubectl
args:
- oidc-login
- get-token
- --oidc-issuer-url=ISSUER_URL
- --oidc-client-id=YOUR_CLIENT_ID
```
--------------------------------
### Setup command to inspect ID token claims
Source: https://github.com/int128/kubelogin/blob/master/README.md
Run this command to retrieve and display the claims present in an ID token obtained from your OIDC provider. Useful for debugging and verifying token contents.
```console
% kubectl oidc-login setup --oidc-issuer-url=ISSUER_URL --oidc-client-id=REDACTED
...
You got a token with the following claims:
{
"sub": "********",
"iss": "https://accounts.google.com",
"aud": "********",
...
}
```
--------------------------------
### Kubelogin Docker Configuration
Source: https://github.com/int128/kubelogin/blob/master/docs/usage.md
Example kubeconfig entry for running kubelogin as a Docker container. It maps local ports and volumes for token caching and specifies OIDC provider details.
```yaml
users:
- name: oidc
user:
exec:
apiVersion: client.authentication.k8s.io/v1
command: docker
args:
- run
- --rm
- -v
- /tmp/.token-cache:/.token-cache
- -p
- 8000:8000
- ghcr.io/int128/kubelogin
- get-token
- --token-cache-dir=/.token-cache
- --listen-address=0.0.0.0:8000
- --oidc-issuer-url=ISSUER_URL
- --oidc-client-id=YOUR_CLIENT_ID
- --oidc-client-secret=YOUR_CLIENT_SECRET
```
--------------------------------
### Example Usage of EncodeRS256 for Testing
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Demonstrates how to use the EncodeRS256 utility to create a signed JWT for testing purposes. The generated token can be used in tests, but actual verification requires the corresponding public key.
```go
privateKey, _ := rsa.GenerateKey(rand.Reader, 2048)
tokenString, _ := testing_jwt.EncodeRS256(privateKey, map[string]interface{}{
"sub": "user@example.com",
"exp": time.Now().Add(time.Hour).Unix(),
"aud": "client_id",
})
// Token can be used in tests as a valid-looking token
// Actual verification still requires matching public key
```
--------------------------------
### Kubectl OIDC Login Command Usage
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Example command-line usage for `kubectl oidc-login`. This command loads kubeconfig, performs OIDC authentication, and updates the kubeconfig with new tokens, enabling subsequent `kubectl` commands to run without further authentication.
```bash
kubectl oidc-login \
--kubeconfig=~/.kube/config \
--context=my-cluster \
--oidc-issuer-url=https://accounts.google.com \
--oidc-client-id=YOUR_CLIENT_ID
```
--------------------------------
### Application Main Function
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
The `main` function initializes the command handler using `di.NewCmd` and runs the application, exiting with the appropriate status code.
```go
// main.go
func main() {
cmd := di.NewCmd()
exitCode := cmd.Run(ctx, os.Args, version)
os.Exit(exitCode)
}
```
--------------------------------
### Check Prerequisites
Source: https://github.com/int128/kubelogin/blob/master/acceptance_test/README.md
Verify that all necessary tools (Docker, Kind, kubectl) are available for the test.
```sh
make check
```
--------------------------------
### Run System Test with Make
Source: https://github.com/int128/kubelogin/blob/master/system_test/README.md
Execute the automated system test for kubelogin using the make command. Ensure Docker, Kind, and Chrome are set up, and necessary host entries and certificates are configured.
```shell
make
```
--------------------------------
### Using Clock interface for testing and production
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Demonstrates the usage of the Clock interface with both a production 'Real' clock implementation and a 'Mock' clock for predictable testing scenarios. This highlights the interface's role in testability.
```go
// Production
clock := &infrastructure_clock.Real{}
if claims.IsExpired(clock) {
// Token expired
}
// Testing
mockClock := &testing_clock.Mock{
Time: time.Unix(1700000000, 0),
}
if claims.IsExpired(mockClock) {
// Predictable time-based testing
}
```
--------------------------------
### Clock Interface
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Provides a way to get the current time, allowing for mockable time retrieval in tests.
```APIDOC
## Now
### Description
Returns the current system time. This method is part of the Clock interface, which allows for time to be mocked in tests.
### Method
`Now() time.Time`
### Returns
- `time.Time` - The current local time.
### Use
Primarily used in production code or as the default implementation for obtaining the current time.
### Example
```go
clock := &clock.Real{}
if claims.IsExpired(clock) {
// Token has expired
}
```
```
--------------------------------
### Clean Command Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/03-cli-reference.md
Use this command to delete all cached tokens. Specify the token cache directory if it differs from the default.
```bash
kubectl oidc-login clean --token-cache-dir=~/.kube/cache/oidc-login
```
--------------------------------
### Kubeconfig After Standalone Update
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Example of a kubeconfig user section after being updated by the standalone kubelogin command. It includes the obtained id-token and refresh-token.
```yaml
users:
- name: my-oidc-user
user:
auth-provider:
name: oidc
config:
idp-issuer-url: https://accounts.google.com
client-id: YOUR_CLIENT_ID.apps.googleusercontent.com
client-secret: YOUR_CLIENT_SECRET
id-token: eyJhbGciOiJSUzI1NiI...
refresh-token: Eby8vdM02xNcWQ7C...
```
--------------------------------
### Kubeconfig Before Standalone Update
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Example of a kubeconfig user section before being updated by the standalone kubelogin command. It shows the OIDC auth-provider configuration.
```yaml
users:
- name: my-oidc-user
user:
auth-provider:
name: oidc
config:
idp-issuer-url: https://accounts.google.com
client-id: YOUR_CLIENT_ID.apps.googleusercontent.com
client-secret: YOUR_CLIENT_SECRET
```
--------------------------------
### Add New Dependency with Wire
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Demonstrates adding a new authentication flow dependency using Wire. This involves defining the struct, adding a Wire set for it, and including it in the main dependency set in `pkg/di/di.go`. Finally, regenerate Wire configurations.
```go
// pkg/usecases/authentication/oauth2implicit/implicit.go
type OAuth2Implicit struct {
Logger logger.Interface
// ...
}
var Set = wire.NewSet(
wire.Struct(new(OAuth2Implicit), "*"),
)
// Add to main Set in pkg/di/di.go
var Set = wire.NewSet(
// ... existing ...
oauth2implicit.Set, // NEW
)
// Regenerate wire
go run github.com/google/wire/cmd/wire ./pkg/di
```
--------------------------------
### JWT Header JSON Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
The header segment is a base64url-encoded JSON object containing metadata about the token, such as the signing algorithm and key ID.
```json
{
"alg": "RS256",
"kid": "1"
}
```
--------------------------------
### Run Kubelogin for Authentication
Source: https://github.com/int128/kubelogin/blob/master/docs/standalone-mode.md
Execute Kubelogin to initiate the authentication process. This command can be run directly or as a kubectl plugin. It will automatically open a browser for login.
```sh
kubelogin
# or run as a kubectl plugin
kubectl oidc-login
```
--------------------------------
### Load
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/10-kubeconfig-api.md
Loads the entire Kubernetes configuration object from a kubeconfig file.
```APIDOC
## Load
### Description
Loads the entire kubeconfig file.
### Method
GET
### Endpoint
/kubeconfig/load
### Parameters
#### Path Parameters
- **kubeconfig** (string) - Required - Path to kubeconfig file
### Response
#### Success Response (200)
- **api.Config** - The entire kubeconfig object
```
--------------------------------
### Dependency Injection Initialization Functions
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Functions for initializing infrastructure components using Wire. These can be overridden in tests with custom implementations.
```go
// pkg/di
func InitializeLogger() logger.Interface
func InitializeBrowser() browser.Interface
func InitializeClock() clock.Interface
func InitializeReader() reader.Interface
func InitializeStdio() stdio.Interface
```
--------------------------------
### Main Entry Point Function
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
The `NewCmd` function is responsible for creating and configuring the CLI command handler with all necessary dependencies injected.
```go
// pkg/di
func NewCmd() cmd.Interface
```
--------------------------------
### Get Token with Base64-Encoded CA Certificate
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Obtain an OIDC token using a base64-encoded CA certificate for secure communication with the OIDC issuer.
```bash
kubectl oidc-login get-token \
--oidc-issuer-url=https://auth.internal.example.com \
--oidc-client-id=my-client \
--idp-certificate-authority-data=LS0tLS1CRUdJTi...
```
--------------------------------
### JWT Payload JSON Example
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
The payload segment is a base64url-encoded JSON object containing the claims, which are statements about an entity (typically, the user) and additional data.
```json
{
"sub": "user123",
"exp": 1709259200,
"aud": "client_id",
"iss": "https://provider.example.com"
}
```
--------------------------------
### Wire Set Definition for `pkg/usecases/authentication/authentication.go`
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Provides all authentication flow implementations, including sub-flows like AuthCodeBrowser and ROPC.
```go
var Set = wire.NewSet(
wire.Struct(new(Authentication), "*"),
wire.Bind(new(Interface), new(*Authentication)),
wire.Struct(new(authcode.Browser), "*"),
wire.Struct(new(authcode.Keyboard), "*"),
wire.Struct(new(ropc.ROPC), "*"),
wire.Struct(new(devicecode.DeviceCode), "*"),
wire.Struct(new(clientcredentials.ClientCredentials), "*"),
)
```
--------------------------------
### Delegate Authentication in Kubelogin
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/04-credential-plugin-api.md
This Go code demonstrates how the credential plugin delegates authentication to an `authentication.Interface`, passing necessary input and receiving a TokenSet.
```go
type authenticationInput = authentication.Input{
Provider: in.Provider,
GrantOptionSet: in.GrantOptionSet,
CachedTokenSet: cachedTokenSet,
TLSClientConfig: in.TLSClientConfig,
}
output, err := u.Authentication.Do(ctx, authenticationInput)
```
--------------------------------
### Initiate Keyboard Authorization Code Flow
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/07-authentication-flows.md
Executes the authorization code flow for headless environments. It prints the authorization URL to stdout and reads the authorization code from stdin.
```go
keyboard := &authcode.Keyboard{
Reader: &reader.Reader{},
Logger: logger,
}
option := &authcode.KeyboardOption{}
tokenSet, err := keyboard.Do(ctx, option, oidcClient)
// Prints: Open https://accounts.google.com/o/oauth2/v2/auth?...
// User manually enters returned code
```
--------------------------------
### Main Wire Configuration Set
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Define a wire.NewSet to group all providers for the application. This set is then used in the wire.Build function to configure the dependency injection graph.
```go
// pkg/di/di.go
var Set = wire.NewSet(
cmd.Set,
usecases.Set,
authentication.Set,
credentialplugin.Set,
setup.Set,
clean.Set,
standalone.Set,
oidc_client.Set,
tokencache_repository.Set,
kubeconfig_loader.Set,
kubeconfig_writer.Set,
tlsclientconfig_loader.Set,
reader.Set,
stdio.Set,
logger.Set,
browser.Set,
clock.Set,
)
func NewCmd() cmd.Interface {
wire.Build(Set)
return nil // Wire replaces this
}
```
--------------------------------
### Kubelogin Main Commands
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/00-index.md
Lists the primary commands available in the kubelogin CLI for managing OIDC authentication with Kubernetes.
```bash
# Get or refresh authentication token (for credential plugin)
kubectl oidc-login get-token [flags]
# Test provider and display token claims
kubectl oidc-login setup [flags]
# Delete cached tokens (logout)
kubectl oidc-login clean [flags]
# Update kubeconfig with tokens (standalone mode)
kubectl oidc-login [flags]
# Print version
kubectl oidc-login version
```
--------------------------------
### Enable Verbose Logging in Kubelogin
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Enable verbose logging to get more detailed debug information during token retrieval. Higher verbosity levels provide more output.
```bash
# Verbosity level 1: Important debug info
kubectl oidc-login get-token -v1 --oidc-issuer-url=...
```
```bash
# Verbosity level 2: More details
kubectl oidc-login get-token -v2 --oidc-issuer-url=...
```
--------------------------------
### Configure Local Server Certificate and Key
Source: https://github.com/int128/kubelogin/blob/master/docs/usage.md
Provide a certificate and private key for the local web server if your identity provider requires HTTPS. Ensure the certificate is valid for localhost.
```yaml
- --local-server-cert=localhost.crt
- --local-server-key=localhost.key
```
--------------------------------
### Extract and unmarshal raw JWT payload
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Example demonstrating how to use DecodePayloadAsRawJSON to obtain the raw payload, then unmarshal it into a map for accessing custom claims like 'roles'.
```go
payload, err := jwt.DecodePayloadAsRawJSON(tokenString)
if err != nil {
return err
}
var customClaims map[string]interface{}
json.Unmarshal(payload, &customClaims)
// Access custom claims not parsed by DecodeWithoutVerify
roles := customClaims["roles"]
```
--------------------------------
### Wire Set Definition for `pkg/oidc/client/factory.go`
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Provides the OIDC client factory and binds it to its interface.
```go
var Set = wire.NewSet(
wire.Struct(new(Factory), "*"),
wire.Bind(new(FactoryInterface), new(*Factory)),
)
```
--------------------------------
### Wire Set Definition for `pkg/tokencache/repository/repository.go`
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Provides the token cache repository and binds its implementation to the repository interface.
```go
var Set = wire.NewSet(
wire.Struct(new(Repository), "*"),
wire.Bind(new(Interface), new(*Repository)),
)
```
--------------------------------
### Keyring Storage Configuration
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/06-token-cache-api.md
Configure the token cache to use the OS-native keyring for secure storage. The directory for storing tokens is also specified.
```go
// OS Keyring storage
config := tokencache.Config{
Directory: filepath.Join(os.Getenv("HOME"), ".kube/cache/oidc-login"),
Storage: tokencache.StorageKeyring,
}
```
--------------------------------
### Wire Set Definition for `pkg/usecases/credentialplugin/get_token.go`
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Provides the credential plugin use case, binding the implementation to its interface.
```go
var Set = wire.NewSet(
wire.Struct(new(GetToken), "*"),
wire.Bind(new(Interface), new(*GetToken)),
)
```
--------------------------------
### Decode JWT payload as raw JSON bytes
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Use DecodePayloadAsRawJSON to get the raw JSON bytes of a JWT's payload. This is useful for custom claim extraction when the standard claims are insufficient.
```go
func DecodePayloadAsRawJSON(s string) ([]byte, error)
```
--------------------------------
### Error Wrapping Best Practice
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Illustrates the best practice for wrapping errors to preserve the error chain. The logger can then unwrap and display the full chain.
```go
if err != nil {
return fmt.Errorf("operation description: %w", err)
}
```
--------------------------------
### PKCE Parameters Structure
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/02-types.md
Holds the parameters for PKCE, including the chosen method and the verifier string.
```go
type Params struct {
Method Method // PKCE method
Verifier string // Verifier string (for S256: generated by oauth2.GenerateVerifier())
}
```
--------------------------------
### Kubernetes Job for Service Account Authentication
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/12-integration-patterns.md
Example of a Kubernetes Job that uses Kubelogin with client credentials grant type to authenticate and apply manifests. Sensitive OIDC parameters are fetched from a Kubernetes Secret.
```yaml
apiVersion: batch/v1
kind: Job
metadata:
name: sync-job
spec:
template:
spec:
serviceAccountName: default
containers:
- name: sync
image: my-sync-image:latest
env:
- name: KUBECONFIG
value: /var/run/secrets/kubernetes.io/serviceaccount/kubeconfig
- name: KUBELOGIN_OIDC_ISSUER_URL
valueFrom:
secretKeyRef:
name: oidc-config
key: issuer-url
- name: KUBELOGIN_OIDC_CLIENT_ID
valueFrom:
secretKeyRef:
name: oidc-config
key: client-id
- name: KUBELOGIN_OIDC_CLIENT_SECRET
valueFrom:
secretKeyRef:
name: oidc-config
key: client-secret
command:
- /bin/sh
- -c
- |
kubectl oidc-login get-token --grant-type=client-credentials
kubectl apply -f manifests/
```
--------------------------------
### Signal Handling with Context
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/09-infrastructure-interfaces.md
Sets up a context that is canceled upon receiving OS interrupt or termination signals. This context cancellation propagates to goroutines for graceful shutdown.
```go
ctx := context.Background()
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer stop()
exitCode := di.NewCmd().Run(ctx, os.Args, version)
```
--------------------------------
### Determine token expiration using a clock
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Example of using the IsExpired method with a real clock to check if a decoded JWT has expired. It demonstrates conditional logic for handling expired tokens, such as prompting for re-authentication.
```go
claims, _ := jwt.DecodeWithoutVerify(tokenString)
systemClock := &clock.Real{}
if claims.IsExpired(systemClock) {
fmt.Println("Token has expired")
// Perform refresh or re-authenticate
} else {
fmt.Println("Token is valid")
}
```
--------------------------------
### Decode JWT and extract claims
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/08-jwt-api.md
Example of using DecodeWithoutVerify to parse a JWT string, retrieve claims like Subject and Expiry, and print them. It also shows how to access the pretty-printed JSON representation of the claims.
```go
tokenString := "eyJhbGciOiJSUzI1NiIsImtpZCI6IjEifQ.eyJzdWIiOiJ1c2VyMTIzIiwiZXhwIjoxNzA5MjU5MjAwfQ.signature_here"
claims, err := jwt.DecodeWithoutVerify(tokenString)
if err != nil {
log.Printf("Could not decode token: %v", err)
return err
}
fmt.Printf("User: %s\n", claims.Subject)
fmt.Printf("Expires: %s\n", claims.Expiry)
fmt.Printf("Token:\n%s\n", claims.Pretty)
```
--------------------------------
### Filesystem Storage Configuration
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/06-token-cache-api.md
Configure the token cache to use filesystem storage. The directory for storing tokens is specified.
```go
// Filesystem storage (default)
config := tokencache.Config{
Directory: filepath.Join(os.Getenv("HOME"), ".kube/cache/oidc-login"),
Storage: tokencache.StorageDisk,
}
```
--------------------------------
### Configure Token Cache Storage
Source: https://github.com/int128/kubelogin/blob/master/docs/usage.md
Change the token cache storage from the default file system to the OS keyring for improved security. Requires the 'go-keyring' library.
```yaml
- --token-cache-storage=keyring
```
--------------------------------
### Get Negotiated PKCE Method
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/05-oidc-client-api.md
Retrieve the Proof Key for Code Exchange (PKCE) method supported by the OpenID Connect provider. This method is used when initiating the authorization code flow to enhance security.
```go
method := oidcClient.NegotiatedPKCEMethod()
pkceParams, err := pkce.New(method)
// Use pkceParams in GetAuthCodeURL or GetTokenByAuthCode
```
--------------------------------
### Generate Wire Dependencies
Source: https://github.com/int128/kubelogin/blob/master/_autodocs/11-dependency-injection.md
Run the Wire command to generate or update the dependency injection code. This command should be executed from the project's root directory.
```bash
cd /workspace/home/kubelogin
go run github.com/google/wire/cmd/wire ./pkg/di
```