Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions example/implicit/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package main

import (
"context"
"flag"
"log"
"os"

"github.com/int128/oauth2cli"
"github.com/int128/oauth2cli/implicit"
"github.com/pkg/browser"
"golang.org/x/oauth2/google"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
)

type cmdOptions struct {
clientID string
localServerCert string
localServerKey string
}

func main() {
var o cmdOptions
flag.StringVar(&o.clientID, "client-id", "", "OAuth Client ID")
flag.StringVar(&o.localServerCert, "local-server-cert", "", "Path to a certificate file for the local server")
flag.StringVar(&o.localServerKey, "local-server-key", "", "Path to a key file for the local server")
flag.Parse()

if o.clientID == "" {
log.Printf(`You need to set oauth2 credentials.
Open https://console.cloud.google.com/apis/credentials and create a client.
Then set the following options:`)
flag.PrintDefaults()
os.Exit(1)
return
}

if o.localServerCert == "" || o.localServerKey == "" {
log.Printf("Certificate and key are required")
flag.PrintDefaults()
os.Exit(1)
return
}

ctx := context.Background()

ready := make(chan string, 1)
var eg errgroup.Group
eg.Go(func() error {
select {
case url, ok := <-ready:
if !ok {
return nil
}
log.Printf("Open %s", url)
if err := browser.OpenURL(url); err != nil {
log.Printf("could not open the browser: %s", err)
}
return nil
case err := <-ctx.Done():
return xerrors.Errorf("context done while waiting for authorization: %w", err)
}
})
eg.Go(func() error {

defer close(ready)
token, nonce, err := oauth2cli.GeTokenIDTokenImplicitly(ctx, &implicit.ServerConfig{
LocalServerPort: []int{8000},
LocalServerReadyChan: ready,
LocalServerCertFile: o.localServerCert,
LocalServerKeyFile: o.localServerKey,
Config: implicit.Config{
ClientID: o.clientID,
AuthURL: google.Endpoint.AuthURL,
RedirectURL: "https://localhost:8000/implicit",
Scopes: []string{"openid"},
},
})
if err != nil {
return xerrors.Errorf("could not get a token: %w", err)
}
log.Printf("You got a valid token: %+v\nnonce: %q", *token, nonce)
return nil
})
if err := eg.Wait(); err != nil {
log.Printf("error while authorization: %s", err)
}
}
5 changes: 3 additions & 2 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package main
import (
"context"
"flag"
"log"
"os"

"github.com/int128/oauth2cli"
"github.com/pkg/browser"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"log"
"os"
)

type cmdOptions struct {
Expand Down
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,20 @@ cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/int128/listener v0.0.0-20191003025026-314d86475e3b h1:7K9Vdxt6paQjHxlQpZ2UgSO68wcYUqVjxZc0rAYCRJg=
github.com/int128/listener v0.0.0-20191003025026-314d86475e3b/go.mod h1:sho0rrH7mNRRZH4hYOYx+xwRDGmtRndaUiu2z9iumes=
github.com/int128/listener v1.0.0 h1:a9H3m4jbXgXpxJUK3fxWrh37Iic/UU/kYOGE0WtjbbI=
github.com/int128/listener v1.0.0/go.mod h1:sho0rrH7mNRRZH4hYOYx+xwRDGmtRndaUiu2z9iumes=
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 h1:49lOXmGaUpV9Fz3gd7TFZY106KVlPVa5jcYD1gaQf98=
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914 h1:jIOcLT9BZzyJ9ce+IwwZ+aF9yeCqzrR+NrD68a/SHKw=
golang.org/x/oauth2 v0.0.0-20190319182350-c85d3e98c914/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e h1:vcxGaoTs7kV8m5Np9uUNQin4BrLOthgV7252N8V+FwY=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522 h1:bhOzK9QyoD0ogCnFro1m2mz41+Ib0oOhfJnBp5MR4K4=
golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
Expand Down
93 changes: 93 additions & 0 deletions implicit.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package oauth2cli

import (
"context"

implict_types "github.com/int128/oauth2cli/implicit"
shared "github.com/int128/oauth2cli/internal"
implicit_int "github.com/int128/oauth2cli/internal/implicit"
"golang.org/x/oauth2"
"golang.org/x/xerrors"
)

// GetTokenImplicitly performs Implicit Grant Flow and returns a token from the provider.
// See https://tools.ietf.org/html/rfc6749#section-4.2
//
// This does the following steps:
//
// 1. Start a local server at the port.
// 2. Open a browser and navigate it to the local server.
// 3. Wait for the user authorization.
// 4. Receive a token via an authorization response (HTTP redirect).
// 5. Post the URL fragment via JavaScript to a local endpoint.
// 6. Return the token.
//
func GetTokenImplicitly(ctx context.Context, c *implict_types.ServerConfig) (token *oauth2.Token, err error) {
if c.LocalServerMiddleware == nil {
c.LocalServerMiddleware = shared.DefaultMiddleware
}
if c.LocalServerSuccessHTML == "" {
c.LocalServerSuccessHTML = DefaultLocalServerSuccessHTML
}
token, _, err = implicit_int.ReceiveTokenViaLocalServer(ctx, c, []string{"token"})
if err != nil {
return token, xerrors.Errorf("error while receiving token: %w", err)
}
return token, err
}

// GetIDTokenImplicitly performs Implicit Grant Flow and returns a id_token from the provider.
// See https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth
//
// This does the following steps:
//
// 1. Start a local server at the port.
// 2. Open a browser and navigate it to the local server.
// 3. Wait for the user authorization.
// 4. Receive a id_token via an authorization response (HTTP redirect).
// 5. Post the URL fragment via JavaScript to a local endpoint.
// 6. Return the id_token.
//
// Note: it's up to the consumer to validate the id_token with the nonce value.
//
func GetIDTokenImplicitly(ctx context.Context, c *implict_types.ServerConfig) (token *oauth2.Token, nonce string, err error) {
if c.LocalServerMiddleware == nil {
c.LocalServerMiddleware = shared.DefaultMiddleware
}
if c.LocalServerSuccessHTML == "" {
c.LocalServerSuccessHTML = DefaultLocalServerSuccessHTML
}
token, nonce, err = implicit_int.ReceiveTokenViaLocalServer(ctx, c, []string{"id_token"})
if err != nil {
return token, nonce, xerrors.Errorf("error while receiving token: %w", err)
}
return token, nonce, err
}

// GeTokenIDTokenImplicitly performs Implicit Grant Flow and returns a token and id_token from the provider.
// See https://openid.net/specs/openid-connect-core-1_0.html#ImplicitFlowAuth
//
// This does the following steps:
//
// 1. Start a local server at the port.
// 2. Open a browser and navigate it to the local server.
// 3. Wait for the user authorization.
// 4. Receive a id_token via an authorization response (HTTP redirect).
// 5. Post the URL fragment via JavaScript to a local endpoint.
// 6. Return the id_token.
//
// Note: it's up to the consumer to validate the id_token with the nonce value.
//
func GeTokenIDTokenImplicitly(ctx context.Context, c *implict_types.ServerConfig) (token *oauth2.Token, nonce string, err error) {
if c.LocalServerMiddleware == nil {
c.LocalServerMiddleware = shared.DefaultMiddleware
}
if c.LocalServerSuccessHTML == "" {
c.LocalServerSuccessHTML = DefaultLocalServerSuccessHTML
}
token, nonce, err = implicit_int.ReceiveTokenViaLocalServer(ctx, c, []string{"token", "id_token"})
if err != nil {
return token, nonce, xerrors.Errorf("error while receiving token: %w", err)
}
return token, nonce, err
}
51 changes: 51 additions & 0 deletions implicit/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package implicit

import (
"net/http"
)

// Config describes a typical OAuth2 Implicit flow, with both the
// client application information and the server's endpoint URLs.
type Config struct {
// ClientID is the application's ID.
ClientID string

// AuthURL represents an OAuth 2.0 provider's authorization endpoint URL.
AuthURL string

// RedirectURL is the URL to redirect users going through
// the OAuth flow, after the resource owner's URLs.
RedirectURL string

// Scope specifies optional requested permissions.
Scopes []string
}

// ServerConfig represents a config for GetToken.
type ServerConfig struct {
Config Config

// Address which the local server binds to.
// Set to "0.0.0.0" to bind all interfaces.
// Default to "127.0.0.1".
LocalServerAddress string
// Candidates of a port which the local server binds to.
// If multiple ports are given, it will try the ports in order.
// If nil or an empty slice is given, it will allocate a free port.
LocalServerPort []int
// A PEM-encoded certificate, and possibly the complete certificate chain.
// When set, the server will serve TLS traffic using the specified
// certificates. It's recommended that the public key's SANs contain
// the loopback addresses - 'localhost', '127.0.0.1' and '::1'
LocalServerCertFile string
// A PEM-encoded private key for the certificate.
// This is required when LocalServerCertFile is set.
LocalServerKeyFile string
// Response HTML body on authorization completed.
// Default to DefaultLocalServerSuccessHTML.
LocalServerSuccessHTML string
// Middleware for the local server. Default to none.
LocalServerMiddleware func(h http.Handler) http.Handler
// A channel to send its URL when the local server is ready. Default to none.
LocalServerReadyChan chan<- string
}
Loading