A Go library for better user experience on OAuth 2.0 and OpenID Connect (OIDC) on CLI. It allows simple and easy user interaction with Authorization Code Grant Flow and a local server.
See GoDoc.
import (
"context"
"log"
"github.com/david972/oauth2cli"
"golang.org/x/oauth2"
)
var endpoint = oauth2.Endpoint{
AuthURL: "https://example.com/oauth2/auth",
TokenURL: "https://example.com/oauth2/token",
}
func main() {
ctx := context.Background()
flow := oauth2cli.AuthCodeFlow{
Config: oauth2.Config{
ClientID: "YOUR_CLIENT_ID",
ClientSecret: "YOUR_CLIENT_SECRET",
Endpoint: endpoint,
Scopes: []string{"email"},
},
}
token, err := flow.GetToken(ctx)
if err != nil {
log.Fatalf("Could not get a token: %s", err)
}
log.Printf("Got a token: %+v", token)
}
Typical OAuth 2.0 Authorization Code Grant implementation requires complicated user interaction. For example,
- User runs the command on a terminal.
- User opens the URL shown on the command.
- User logs in to the provider.
- User copies the code shown on the browser.
- User pastes the code on the terminal.
- User can access to the API using the token.
By using oauth2cli
, user interaction will be simple and easy as follows:
- User runs the command on a terminal.
oauth2cli
opens the browser automatically.- User logs in to the provider.
oauth2cli
gets a token from the provider.- User can access to the API using the token.
oauth2cli
performs the following steps:
- Start a local server at the port.
- Open browser and navigate to the local server.
- Wait for user authorization.
- Receive a code via an authorization response (HTTP redirect).
- Exchange the code and a token.
- Return the code.
This is an open source software licensed under Apache 2.0. Feel free to open issues and pull requests.