-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
78 lines (66 loc) · 1.74 KB
/
main.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
package client
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"golang.org/x/oauth2"
)
var (
config = oauth2.Config{
ClientID: "222222",
ClientSecret: "22222222",
Scopes: []string{"all"},
RedirectURL: "http://localhost:9094/oauth2",
// This points to our Authorization Server
// if our Client ID and Client Secret are valid
// it will attempt to authorize our user
Endpoint: oauth2.Endpoint{
AuthURL: "http://localhost:9096/authorize",
TokenURL: "http://localhost:9096/token",
},
}
)
// Homepage
func HomePage(w http.ResponseWriter, r *http.Request) {
fmt.Println("Homepage Hit!")
u := config.AuthCodeURL("xyz")
http.Redirect(w, r, u, http.StatusFound)
}
// Authorize
func Authorize(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
state := r.Form.Get("state")
if state != "xyz" {
http.Error(w, "State invalid", http.StatusBadRequest)
return
}
code := r.Form.Get("code")
if code == "" {
http.Error(w, "Code not found", http.StatusBadRequest)
return
}
token, err := config.Exchange(context.Background(), code)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
e := json.NewEncoder(w)
e.SetIndent("", " ")
e.Encode(*token)
}
func main() {
// 1 - We attempt to hit our Homepage route
// if we attempt to hit this unauthenticated, it
// will automatically redirect to our Auth
// server and prompt for login credentials
http.HandleFunc("/", HomePage)
// 2 - This displays our state, code and
// token and expiry time that we get back
// from our Authorization server
http.HandleFunc("/oauth2", Authorize)
// 3 - We start up our Client on port 9094
log.Println("Client is running at 9094 port.")
log.Fatal(http.ListenAndServe(":9094", nil))
}