-
Notifications
You must be signed in to change notification settings - Fork 0
/
oauth2-cli.go
153 lines (124 loc) · 3.25 KB
/
oauth2-cli.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"strings"
)
const (
clientGrant = "client_credentials"
passwordGrant = "password"
)
const (
error = 1
success = 0
)
const usage = `Usage of oauth2-cli:
oauth2-cli [opts]
oauth2-cli retrieves an OAuth2 access token using client or password grant
`
func main() {
os.Exit(Run())
}
func Run() int {
host, cid, cpw, uid, upw, typ := parseFlags()
req, e := createRequest(host, cid, cpw, uid, upw, typ)
if e != success {
return e
}
body, e := sendRequest(req)
if e != success {
return e
}
token, e := extractAccessToken(body)
if e != success {
return e
}
fmt.Println(token)
return success
}
func parseFlags() (*string, *string, *string, *string, *string, *string) {
flag.Usage = func() {
printUsageAndExit()
}
host := flag.String("host", "http://localhost:9094/token", "authorization server url")
cid := flag.String("cid", "", "client id")
cpw := flag.String("cpw", "", "client secret")
uid := flag.String("uid", "", "end user id")
upw := flag.String("upw", "", "end user secret")
typ := flag.String("typ", clientGrant, "grant type, can be "+clientGrant+" or "+passwordGrant)
if len(os.Args[1:]) > 0 {
flag.Parse()
} else {
printUsageAndExit()
}
return host, cid, cpw, uid, upw, typ
}
func printUsageAndExit() {
fmt.Fprintf(os.Stdout, usage)
flag.PrintDefaults()
os.Exit(0)
}
func createRequest(host *string, cid *string, cpw *string, uid *string, upw *string, typ *string) (*http.Request, int) {
data := url.Values{}
if *typ == clientGrant {
data.Add("grant_type", clientGrant)
} else if *typ == passwordGrant {
data.Add("grant_type", passwordGrant)
data.Add("username", *uid)
data.Add("password", *upw)
} else {
fmt.Println("Unknown grant type (typ parameter was: '" + *typ + "')")
return nil, error
}
return formDataRequestWithBody(host, cid, cpw, data)
}
func formDataRequestWithBody(host *string, cid *string, cpw *string, data url.Values) (*http.Request, int) {
req, err := http.NewRequest("POST", *host, strings.NewReader(data.Encode()))
if err != nil {
return nil, error
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth(*cid, *cpw)
return req, success
}
func sendRequest(req *http.Request) ([]byte, int) {
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
if res.StatusCode != 200 {
fmt.Fprintf(os.Stderr, "Error response from token endpoint (HTTP Status %d):\n", res.StatusCode)
fmt.Fprintf(os.Stderr, string(body))
return nil, error
}
return body, success
}
type AccessTokenResponse struct {
AccessToken string `json:"access_token"`
Type string `json:"token_type"`
Expiry int `json:"expires_in"`
}
func extractAccessToken(body []byte) (string, int) {
var atr AccessTokenResponse
err := json.Unmarshal(body, &atr)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to parse response: \"")
fmt.Fprintf(os.Stderr, "%s", err)
fmt.Fprintf(os.Stderr, "\"\n")
fmt.Fprintf(os.Stderr, "Response was:\n")
fmt.Fprintf(os.Stderr, string(body)[:200])
fmt.Fprintf(os.Stderr, "...")
return "", error
}
return atr.AccessToken, success
}