-
Notifications
You must be signed in to change notification settings - Fork 1k
oauth2: add device flow support #578
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
Closed
Closed
Changes from all commits
Commits
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 hidden or 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,80 @@ | ||
| package oauth2 | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "io/ioutil" | ||
| "net/http" | ||
| "net/url" | ||
| "strings" | ||
|
|
||
| "golang.org/x/net/context/ctxhttp" | ||
| ) | ||
|
|
||
| const ( | ||
| errAuthorizationPending = "authorization_pending" | ||
| errSlowDown = "slow_down" | ||
| errAccessDenied = "access_denied" | ||
| errExpiredToken = "expired_token" | ||
| ) | ||
|
|
||
| type DeviceAuth struct { | ||
| DeviceCode string `json:"device_code"` | ||
| UserCode string `json:"user_code"` | ||
| VerificationURI string `json:"verification_uri,verification_url"` | ||
| VerificationURIComplete string `json:"verification_uri_complete,omitempty"` | ||
| ExpiresIn int `json:"expires_in"` | ||
| Interval int `json:"interval,omitempty"` | ||
| raw map[string]interface{} | ||
| } | ||
|
|
||
| func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAuth, error) { | ||
| req, err := http.NewRequest("POST", c.Endpoint.DeviceAuthURL, strings.NewReader(v.Encode())) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| req.Header.Set("Content-Type", "application/x-www-form-urlencoded") | ||
|
|
||
| r, err := ctxhttp.Do(ctx, nil, req) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) | ||
| if err != nil { | ||
| return nil, fmt.Errorf("oauth2: cannot auth device: %v", err) | ||
| } | ||
| if code := r.StatusCode; code < 200 || code > 299 { | ||
| return nil, &RetrieveError{ | ||
| Response: r, | ||
| Body: body, | ||
| } | ||
| } | ||
|
|
||
| da := &DeviceAuth{} | ||
| err = json.Unmarshal(body, &da) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| _ = json.Unmarshal(body, &da.raw) | ||
|
|
||
| // Azure AD supplies verification_url instead of verification_uri | ||
| if da.VerificationURI == "" { | ||
| da.VerificationURI, _ = da.raw["verification_url"].(string) | ||
| } | ||
|
|
||
| return da, nil | ||
| } | ||
|
|
||
| func parseError(err error) string { | ||
| e, ok := err.(*RetrieveError) | ||
| if ok { | ||
| eResp := make(map[string]string) | ||
| _ = json.Unmarshal(e.Body, &eResp) | ||
| return eResp["error"] | ||
| } | ||
| return "" | ||
| } |
This file contains hidden or 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 |
|---|---|---|
|
|
@@ -16,6 +16,7 @@ import ( | |
| "net/url" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
|
|
||
| "golang.org/x/oauth2/internal" | ||
| ) | ||
|
|
@@ -70,8 +71,9 @@ type TokenSource interface { | |
| // Endpoint represents an OAuth 2.0 provider's authorization and token | ||
| // endpoint URLs. | ||
| type Endpoint struct { | ||
| AuthURL string | ||
| TokenURL string | ||
| AuthURL string | ||
| DeviceAuthURL string | ||
| TokenURL string | ||
|
|
||
| // AuthStyle optionally specifies how the endpoint wants the | ||
| // client ID & client secret sent. The zero value means to | ||
|
|
@@ -224,6 +226,62 @@ func (c *Config) Exchange(ctx context.Context, code string, opts ...AuthCodeOpti | |
| return retrieveToken(ctx, c, v) | ||
| } | ||
|
|
||
| // AuthDevice returns a device auth struct which contains a device code | ||
| // and authorization information provided for users to enter on another device. | ||
| func (c *Config) AuthDevice(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuth, error) { | ||
| v := url.Values{ | ||
| "client_id": {c.ClientID}, | ||
| } | ||
| if len(c.Scopes) > 0 { | ||
| v.Set("scope", strings.Join(c.Scopes, " ")) | ||
| } | ||
| for _, opt := range opts { | ||
| opt.setValue(v) | ||
| } | ||
| return retrieveDeviceAuth(ctx, c, v) | ||
| } | ||
|
|
||
| // Poll does a polling to exchange an device code for a token. | ||
| func (c *Config) Poll(ctx context.Context, da *DeviceAuth, opts ...AuthCodeOption) (*Token, error) { | ||
| v := url.Values{ | ||
| "client_id": {c.ClientID}, | ||
| "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, | ||
| "device_code": {da.DeviceCode}, | ||
| } | ||
| if len(c.Scopes) > 0 { | ||
| v.Set("scope", strings.Join(c.Scopes, " ")) | ||
| } | ||
| for _, opt := range opts { | ||
| opt.setValue(v) | ||
| } | ||
|
|
||
| // If no interval was provided, the client MUST use a reasonable default polling interval. | ||
| // See https://tools.ietf.org/html/draft-ietf-oauth-device-flow-07#section-3.5 | ||
| interval := da.Interval | ||
| if interval == 0 { | ||
| interval = 5 | ||
| } | ||
|
|
||
| for { | ||
| time.Sleep(time.Duration(interval) * time.Second) | ||
|
|
||
| tok, err := retrieveToken(ctx, c, v) | ||
| if err == nil { | ||
| return tok, nil | ||
| } | ||
|
|
||
| errTyp := parseError(err) | ||
| switch errTyp { | ||
| case errAccessDenied, errExpiredToken: | ||
| return tok, errors.New("oauth2: " + errTyp) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be more convenient to immediately return a specialized error There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we are returning the error here. Not sure what the proposal currently is |
||
| case errSlowDown: | ||
| interval += 1 | ||
| fallthrough | ||
| case errAuthorizationPending: | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Client returns an HTTP client using the provided token. | ||
| // The token will auto-refresh as necessary. The underlying | ||
| // HTTP transport will be obtained using the provided context. | ||
|
|
@@ -271,7 +329,6 @@ func (tf *tokenRefresher) Token() (*Token, error) { | |
| "grant_type": {"refresh_token"}, | ||
| "refresh_token": {tf.refreshToken}, | ||
| }) | ||
|
|
||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
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.
and need fix this comment #356 (comment)
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.
I think the best solution would be to give the error or the token back, and the caller will decide how and how many times to call
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.
the spec doesn't say that an error should be returned if the interval is not particularly specified. In most of the cases, the auth service should return this value. Setting the default interval to a safe value seems to me that's ok.