-
Notifications
You must be signed in to change notification settings - Fork 55
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
Changes from 1 commit
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
25a6de3
feat: device auth
jfatta 6e1b7a0
fix:linter
jfatta 72222c0
feat: parse tenant from the token
jfatta db6ba82
fix: lint
jfatta f6ecf97
fix: scope const
jfatta 231e002
Merge branch 'main' into feat-device-auth
jfatta 5c6057f
refactor: split auth flow (start + wait)
jfatta 122d5b9
"fix: error handling"
jfatta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}, | ||
"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() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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...
There was a problem hiding this comment.
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.