Skip to content

OAuth2 Support in Cobra Through Integration or Libraries #2217

Open
@michaelbeutler

Description

@michaelbeutler

While building an internal CLI tool with Cobra, I needed to integrate authentication with our backend services using OAuth2. Specifically, I was looking to implement the [device authorization flow](https://datatracker.ietf.org/doc/html/rfc8628). However, I found that there wasn’t an easy-to-use library for this purpose that integrates well with Cobra.

Suggestion

To address this, I started developing a library, [cobra-oauth2](https://github.com/nauthera/cobra-oauth2), aimed at simplifying the integration of OAuth2 flows into Cobra-based CLI tools. The library is in its early stages and currently supports basic features, but it is designed to be easy to use and extend.

Here’s a basic example of how to use cobra-oauth2:

demo

Example Usage

1. Main Application Setup

Define your main entry point and execute your Cobra CLI:

package main

import "github.com/nauthera/cobra-oauth2/examples/basic/cmd"

func main() {
	cmd.Execute()
}

2. Root Command Setup

Set up the root command and initialize OAuth2 commands:

package cmd

import (
	"net/url"
	"os"

	"github.com/nauthera/cobra-oauth2/pkg/auth"
	"github.com/nauthera/cobra-oauth2/pkg/storage"
	"github.com/spf13/cobra"
)

const CLIENT_ID = "my-client-id"

var rootCmd = &cobra.Command{
	Use: "cobra-oauth2",
}

func Execute() {
	err := rootCmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

func init() {
	discoveryUrl, err := url.Parse("https://foo-bar.nauthera.io/.well-known/openid-configuration")
	if err != nil {
		rootCmd.PrintErr("error parsing discovery URL: ", err)
		return
	}

	storageProvider := storage.NewKeyringStorage(CLIENT_ID)

	options := []auth.Option{
		auth.WithDiscoveryURL(*discoveryUrl),
		auth.WithClientID(CLIENT_ID),
		auth.WithStorageProvider(storageProvider),
	}

	rootCmd.AddCommand(
		auth.NewLoginCommand(options...),
		auth.NewTokenCommand(options...),
		auth.NewLogoutCommand(options...),
	)
}

Question for the Community

  1. Is there a specific need or demand for an OAuth2 library that integrates seamlessly with Cobra?
  2. Does Cobra’s core maintainers or the community recommend any existing solutions I may have overlooked?
  3. Would it make sense to provide guidance on how to handle such cases?

Contribution

I’d love feedback on the design and implementation of cobra-oauth2. Contributions and ideas for extending its capabilities (e.g., support for additional OAuth2 flows, enhanced storage mechanisms, etc.) are welcome!

Repo: https://github.com/nauthera/cobra-oauth2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions