-
Notifications
You must be signed in to change notification settings - Fork 29
/
oauth2_device.go
100 lines (76 loc) · 2.19 KB
/
oauth2_device.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package cmd
import (
"context"
"errors"
"net/http"
"time"
"github.com/cloudentity/oauth2c/internal/oauth2"
"github.com/pkg/browser"
)
func (c *OAuth2Cmd) DeviceGrantFlow(clientConfig oauth2.ClientConfig, serverConfig oauth2.ServerConfig, hc *http.Client) error {
var (
authorizationRequest oauth2.Request
authorizationResponse oauth2.DeviceAuthorizationResponse
tokenRequest oauth2.Request
tokenResponse oauth2.TokenResponse
err error
)
LogHeader("Device Flow")
// device authorization endpoint
LogSection("Request device authorization")
if authorizationRequest, authorizationResponse, err = oauth2.RequestDeviceAuthorization(context.Background(), clientConfig, serverConfig, hc); err != nil {
LogRequestAndResponseln(tokenRequest, err)
return err
}
LogRequestAndResponse(authorizationRequest, authorizationResponse)
Logfln("\nOpen the following URL:\n\n%s\n", authorizationResponse.VerificationURIComplete)
if err = browser.OpenURL(authorizationResponse.VerificationURIComplete); err != nil {
LogError(err)
}
Logln()
// polling
tokenStatus := LogAction("Waiting for token. Go to the browser to authenticate...")
ticker := time.NewTicker(time.Duration(authorizationResponse.Interval) * time.Second)
done := make(chan error)
go func() {
var oauth2Error *oauth2.Error
defer close(done)
for {
select {
case <-done:
return
case <-ticker.C:
if tokenRequest, tokenResponse, err = oauth2.RequestToken(
context.Background(),
clientConfig,
serverConfig,
hc,
oauth2.WithDeviceCode(authorizationResponse.DeviceCode),
); err != nil {
if errors.As(err, &oauth2Error) {
switch oauth2Error.ErrorCode {
case oauth2.ErrAuthorizationPending, oauth2.ErrSlowDown:
continue
}
}
done <- err
return
} else {
return
}
}
}
}()
err = <-done
LogSection("Exchange device code for token")
if err != nil {
LogRequestAndResponseln(tokenRequest, err)
return err
}
LogAuthMethod(clientConfig)
LogRequestAndResponse(tokenRequest, tokenResponse)
LogTokenPayloadln(tokenResponse)
c.PrintResult(tokenResponse)
tokenStatus("Obtained token")
return nil
}