Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: device auth #9

Merged
merged 8 commits into from
Jan 22, 2021
Merged
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
153 changes: 153 additions & 0 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package auth

import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os/exec"
"runtime"
"time"
)

// 1st request
// curl --request POST \
// --url 'https://auth0.auth0.com/oauth/device/code' \
// --header 'content-type: application/x-www-form-urlencoded' \
// --data 'client_id=2iZo3Uczt5LFHacKdM0zzgUO2eG2uDjT' \
// --data 'scope=openid read:roles' \
// --data audience=https://\*.auth0.com/api/v2/

// polling request
// curl --request POST \
// --url 'https://auth0.auth0.com/oauth/token' \
// --header 'content-type: application/x-www-form-urlencoded' \
// --data grant_type=urn:ietf:params:oauth:grant-type:device_code \
// --data device_code=9GtgUcsGKzXkU-i70RN74baY \
// --data 'client_id=2iZo3Uczt5LFHacKdM0zzgUO2eG2uDjT'
const (
clientID = "2iZo3Uczt5LFHacKdM0zzgUO2eG2uDjT"
deviceCodeEndpoint = "https://auth0.auth0.com/oauth/device/code"
oauthTokenEndpoint = "https://auth0.auth0.com/oauth/token"
)

type Authenticator struct {
}

type Result struct {
Tenant string
AccessToken string
ExpiresIn int64
}

type deviceCodeResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}

func (d *deviceCodeResponse) IntervalDuration() time.Duration {
return time.Duration(d.Interval) * time.Second
}

func (a *Authenticator) Authenticate(ctx context.Context) (Result, error) {
dcr, err := a.getDeviceCode(ctx)
if err != nil {
return Result{}, fmt.Errorf("cannot get device code: %w", err)
}

fmt.Printf("Your pairing code is: %s\n", dcr.UserCode)
openURL(dcr.VerificationURI)

return a.awaitResponse(ctx, dcr)
}

func (a *Authenticator) getDeviceCode(ctx context.Context) (*deviceCodeResponse, error) {
data := url.Values{
"client_id": {clientID},
"scope": {"openid read:roles"},
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

scope should be a const openid profile read:clients create:clients...

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done. Let's extend the scope needed as we add new operations.

"audience": {"https://*.auth0.com/api/v2/"},
}
r, err := http.PostForm(deviceCodeEndpoint, data)
if err != nil {
return nil, fmt.Errorf("cannot get device code: %w", err)
}
defer r.Body.Close()
var res deviceCodeResponse
err = json.NewDecoder(r.Body).Decode(&res)
if err != nil {
return nil, fmt.Errorf("cannot decode response: %w", err)
}

return &res, nil
}

func (a *Authenticator) awaitResponse(ctx context.Context, dcr *deviceCodeResponse) (Result, error) {
t := time.NewTicker(dcr.IntervalDuration())
for {
select {
case <-ctx.Done():
return Result{}, ctx.Err()
case <-t.C:
data := url.Values{
"client_id": {clientID},
"grant_type": {"urn:ietf:params:oauth:grant-type:device_code"},
"device_code": {dcr.DeviceCode},
}
r, err := http.PostForm(oauthTokenEndpoint, data)
if err != nil {
return Result{}, fmt.Errorf("cannot get device code: %w", err)
}
defer r.Body.Close()

var res struct {
AccessToken string `json:"access_token"`
IDToken string `json:"id_token"`
Scope string `json:"scope"`
ExpiresIn int64 `json:"expires_in"`
TokenType string `json:"token_type"`
Error *string `json:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty"`
}

err = json.NewDecoder(r.Body).Decode(&res)
if err != nil {
return Result{}, fmt.Errorf("cannot decode response: %w", err)
}

if res.Error != nil {
if *res.Error == "authorization_pending" {
continue
}
return Result{}, errors.New(res.ErrorDescription)
}

// TODO(jfatta): parse tenant information from the access token (JWT)
return Result{
AccessToken: res.AccessToken,
ExpiresIn: res.ExpiresIn,
}, nil
}
}
}

func openURL(url string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}
25 changes: 25 additions & 0 deletions internal/cli/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package cli

import (
"github.com/auth0/auth0-cli/internal/auth"
"github.com/spf13/cobra"
)

func loginCmd(cli *cli) *cobra.Command {
cmd := &cobra.Command{
Use: "login",
Short: "authenticate the Auth0 CLI.",
RunE: func(cmd *cobra.Command, args []string) error {
a := &auth.Authenticator{}
_, err := a.Authenticate(cmd.Context())
if err != nil {
return err
}
// TODO(jfatta): update the configuration with the token, tenant, audience, etc
cli.renderer.Infof("successfully logged in.")
return nil
},
}

return cmd
}
4 changes: 3 additions & 1 deletion internal/cli/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"context"
"os"

"github.com/auth0/auth0-cli/internal/display"
Expand Down Expand Up @@ -44,13 +45,14 @@ func Execute() {
rootCmd.PersistentFlags().BoolVar(&cli.verbose,
"verbose", false, "Enable verbose mode.")

rootCmd.AddCommand(loginCmd(cli))
rootCmd.AddCommand(clientsCmd(cli))

// TODO(cyx): backport this later on using latest auth0/v5.
// rootCmd.AddCommand(actionsCmd(cli))
// rootCmd.AddCommand(triggersCmd(cli))

if err := rootCmd.Execute(); err != nil {
if err := rootCmd.ExecuteContext(context.TODO()); err != nil {
cli.renderer.Errorf(err.Error())
os.Exit(1)
}
Expand Down