forked from go-oauth2/oauth2
/
client.go
55 lines (49 loc) · 1.19 KB
/
client.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
package main
import (
"context"
"encoding/json"
"log"
"net/http"
"golang.org/x/oauth2"
)
var (
config = oauth2.Config{
ClientID: "222222",
ClientSecret: "22222222",
Scopes: []string{"all"},
RedirectURL: "http://localhost:9094/oauth2",
Endpoint: oauth2.Endpoint{
AuthURL: "http://localhost:9096/authorize",
TokenURL: "http://localhost:9096/token",
},
}
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
u := config.AuthCodeURL("xyz")
http.Redirect(w, r, u, http.StatusFound)
})
http.HandleFunc("/oauth2", func(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)
})
log.Println("Client is running at 9094 port.")
log.Fatal(http.ListenAndServe(":9094", nil))
}