-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
290 lines (234 loc) · 6.5 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package main
import (
"context"
"crypto/rand"
"encoding/base64"
"log"
"net/http"
"os"
"strings"
"github.com/coreos/go-oidc"
"golang.org/x/oauth2"
"gopkg.in/yaml.v3"
)
var config struct {
ClientID string
ClientSecret string
Scopes []string
RedirectURL string
ProviderURL string
SessionStoreSecret string
}
func init() {
config.ClientID = os.Getenv("OIDC_CLIENT_ID")
config.ClientSecret = os.Getenv("OIDC_CLIENT_SECRET")
config.Scopes = strings.Split(os.Getenv("OIDC_SCOPES"), ",")
config.RedirectURL = os.Getenv("OIDC_REDIRECT_URL")
config.ProviderURL = os.Getenv("OIDC_PROVIDER_URL")
config.SessionStoreSecret = os.Getenv("SESSION_STORE_SECRET")
if config.SessionStoreSecret == "" {
config.SessionStoreSecret = "very-secure-secret"
}
}
type Authenticator struct {
Provider *oidc.Provider
Config oauth2.Config
Ctx context.Context
}
func NewAuthenticator() (*Authenticator, error) {
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, config.ProviderURL)
if err != nil {
log.Printf("failed to get provider: %v", err)
return nil, err
}
conf := oauth2.Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
RedirectURL: config.RedirectURL,
Endpoint: provider.Endpoint(),
Scopes: config.Scopes,
}
return &Authenticator{
Provider: provider,
Config: conf,
Ctx: ctx,
}, nil
}
func CallbackHandler(w http.ResponseWriter, r *http.Request) {
session, err := Store.Get(r, "auth-session")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if r.URL.Query().Get("state") != session.Values["state"] {
http.Error(w, "Invalid state parameter", http.StatusBadRequest)
return
}
authenticator, err := NewAuthenticator()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
token, err := authenticator.Config.Exchange(context.TODO(), r.URL.Query().Get("code"))
if err != nil {
log.Printf("no token found: %v", err)
w.WriteHeader(http.StatusUnauthorized)
return
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
http.Error(w, "No id_token field in oauth2 token.", http.StatusInternalServerError)
return
}
oidcConfig := &oidc.Config{
ClientID: config.ClientID,
}
idToken, err := authenticator.Provider.Verifier(oidcConfig).Verify(context.TODO(), rawIDToken)
if err != nil {
http.Error(w, "Failed to verify ID Token: "+err.Error(), http.StatusInternalServerError)
return
}
// Getting now the userInfo
var profile map[string]interface{}
if err := idToken.Claims(&profile); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session.Values["id_token"] = rawIDToken
session.Values["access_token"] = token.AccessToken
session.Values["refresh_token"] = token.RefreshToken
session.Values["profile"] = profile
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Redirect to logged in page
http.Redirect(w, r, "/user", http.StatusSeeOther)
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
// Generate random state
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
state := base64.StdEncoding.EncodeToString(b)
session, err := Store.Get(r, "auth-session")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
session.Values["state"] = state
err = session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
authenticator, err := NewAuthenticator()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, authenticator.Config.AuthCodeURL(state), http.StatusTemporaryRedirect)
}
func UserinfoHandler(rw http.ResponseWriter, req *http.Request) {
session, err := Store.Get(req, "auth-session")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
if session.IsNew {
http.Redirect(rw, req, "/login", http.StatusTemporaryRedirect)
return
}
idTokenI, ok := session.Values["id_token"]
if !ok {
http.Redirect(rw, req, "/login", http.StatusTemporaryRedirect)
return
}
idToken := idTokenI.(string)
refreshTokenI, ok := session.Values["refresh_token"]
if !ok {
http.Redirect(rw, req, "/login", http.StatusTemporaryRedirect)
return
}
refreshToken := refreshTokenI.(string)
type Config struct {
ClientID string `yaml:"client-id"`
ClientSecret string `yaml:"client-secret"`
IDToken string `yaml:"id-token"`
IdpCertificateAuthority string `yaml:"idp-certificate-authority,omitempty"`
IdpIssuerURL string `yaml:"idp-issuer-url"`
RefreshToken string `yaml:"refresh-token"`
}
type AuthProvider struct {
Config *Config `yaml:"config"`
Name string `yaml:"name"`
}
type UserConfig struct {
AuthProvider *AuthProvider `yaml:"auth-provider"`
}
type User struct {
Name string `yaml:"name"`
User *UserConfig `yaml:"user"`
}
type UserContext struct {
Users []*User `yaml:"users"`
}
uc := &UserContext{
Users: []*User{
{
Name: "openid-connect",
User: &UserConfig{
AuthProvider: &AuthProvider{
Name: "oidc",
Config: &Config{
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
IDToken: idToken,
IdpIssuerURL: config.ProviderURL,
RefreshToken: refreshToken,
},
},
},
},
},
}
rw.Header().Set("Content-Tyep", "application/yaml;charset=UTF-8")
encoder := yaml.NewEncoder(rw)
encoder.SetIndent(2)
encoder.Encode(uc)
}
func main() {
Init()
mux := http.NewServeMux()
mux.HandleFunc("/login", LoginHandler)
mux.HandleFunc("/callback", CallbackHandler)
mux.HandleFunc("/userinfo", UserinfoHandler)
mux.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
if req.Method != "GET" && req.URL.Path != "/" {
http.NotFound(rw, req)
return
}
session, err := Store.Get(req, "auth-session")
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
session.Save(req, rw)
_, found := session.Values["id_token"]
if found {
http.Redirect(rw, req, "/userinfo", http.StatusTemporaryRedirect)
} else {
http.Redirect(rw, req, "/login", http.StatusTemporaryRedirect)
}
})
port := "80"
if p, found := os.LookupEnv("PORT"); found {
port = p
}
http.ListenAndServe(":"+port, mux)
}