-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.go
226 lines (185 loc) · 5.31 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
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"crypto/sha256"
"encoding/base64"
"encoding/gob"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"os"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/gorilla/sessions"
_ "golang.org/x/net/context"
"golang.org/x/oauth2"
)
const (
redirectURI string = "http://localhost:8080/callback"
)
// Authentication + Encryption key pairs
var sessionStoreKeyPairs = [][]byte{
[]byte("something-very-secret"),
nil,
}
var store sessions.Store
var (
clientID string
config *oauth2.Config
)
type User struct {
Email string
DisplayName string
}
func init() {
// Create file system store with no size limit
fsStore := sessions.NewFilesystemStore("", sessionStoreKeyPairs...)
fsStore.MaxLength(0)
store = fsStore
gob.Register(&User{})
gob.Register(&oauth2.Token{})
}
func main() {
log.SetFlags(log.LstdFlags | log.Llongfile)
clientID = os.Getenv("AZURE_AD_CLIENT_ID")
if clientID == "" {
log.Fatal("AZURE_AD_CLIENT_ID must be set.")
}
config = &oauth2.Config{
ClientID: clientID,
ClientSecret: "", // no client secret
RedirectURL: redirectURI,
Endpoint: oauth2.Endpoint{
AuthURL: "https://login.microsoftonline.com/common/oauth2/authorize",
TokenURL: "https://login.microsoftonline.com/common/oauth2/token",
},
Scopes: []string{"User.Read"},
}
http.Handle("/", handle(IndexHandler))
http.Handle("/callback", handle(CallbackHandler))
log.Fatal(http.ListenAndServe(":8080", nil))
}
type handle func(w http.ResponseWriter, req *http.Request) error
func (h handle) ServeHTTP(w http.ResponseWriter, req *http.Request) {
defer func() {
if r := recover(); r != nil {
log.Printf("Handler panic: %v", r)
}
}()
if err := h(w, req); err != nil {
log.Printf("Handler error: %v", err)
if httpErr, ok := err.(Error); ok {
http.Error(w, httpErr.Message, httpErr.Code)
}
}
}
type Error struct {
Code int
Message string
}
func (e Error) Error() string {
if e.Message == "" {
e.Message = http.StatusText(e.Code)
}
return fmt.Sprintf("%d: %s", e.Code, e.Message)
}
func IndexHandler(w http.ResponseWriter, req *http.Request) error {
session, _ := store.Get(req, "session")
var token *oauth2.Token
if req.FormValue("logout") != "" {
session.Values["token"] = nil
sessions.Save(req, w)
} else {
if v, ok := session.Values["token"]; ok {
token = v.(*oauth2.Token)
}
}
var data = struct {
Token *oauth2.Token
AuthURL string
}{
Token: token,
AuthURL: config.AuthCodeURL(SessionState(session), oauth2.AccessTypeOnline),
}
return indexTempl.Execute(w, &data)
}
var indexTempl = template.Must(template.New("").Parse(`<!DOCTYPE html>
<html>
<head>
<title>Azure AD OAuth2 Example</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body class="container-fluid">
<div class="row">
<div class="col-xs-4 col-xs-offset-4">
<h1>Azure AD OAuth2 Example</h1>
{{with .Token}}
<div id="displayName"></div>
<a href="/?logout=true">Logout</a>
{{else}}
<a href="{{$.AuthURL}}">Login</a>
{{end}}
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
{{with .Token}}
var token = {{.}};
$.ajax({
url: 'https://graph.windows.net/me?api-version=1.6',
dataType: 'json',
success: function(data, status) {
$('#displayName').text('Welcome ' + data.displayName);
},
beforeSend: function(xhr, settings) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token);
}
});
{{end}}
</script>
</body>
</html>
`))
func CallbackHandler(w http.ResponseWriter, req *http.Request) error {
session, _ := store.Get(req, "session")
if req.FormValue("state") != SessionState(session) {
return Error{http.StatusBadRequest, "invalid callback state"}
}
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("client_id", clientID)
form.Set("code", req.FormValue("code"))
form.Set("redirect_uri", redirectURI)
form.Set("resource", "https://graph.windows.net")
tokenReq, err := http.NewRequest(http.MethodPost, config.Endpoint.TokenURL, strings.NewReader(form.Encode()))
if err != nil {
return fmt.Errorf("error creating token request: %v", err)
}
tokenReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(tokenReq)
if err != nil {
return fmt.Errorf("error performing token request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("token response was %s", resp.Status)
}
var token oauth2.Token
if err := json.NewDecoder(resp.Body).Decode(&token); err != nil {
return fmt.Errorf("error decoding JSON response: %v", err)
}
session.Values["token"] = &token
if err := sessions.Save(req, w); err != nil {
return fmt.Errorf("error saving session: %v", err)
}
http.Redirect(w, req, "/", http.StatusFound)
return nil
}
func SessionState(session *sessions.Session) string {
return base64.StdEncoding.EncodeToString(sha256.New().Sum([]byte(session.ID)))
}
func dump(v interface{}) {
spew.Dump(v)
}