-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoidc.go
199 lines (154 loc) · 4.7 KB
/
oidc.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
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"net/http"
"os/exec"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/pkg/errors"
"golang.org/x/oauth2"
)
type idTokenResult struct {
RawToken string
Token *oidc.IDToken
Email string
Sub string
}
func (this idTokenResult) Expiry() *time.Time {
return &this.Token.Expiry
}
type idTokenMessage struct { // One of (either)...
result idTokenResult // a result, or
err error // an error
}
func openInBrowser(url string) error {
cmd := exec.Command("open", url)
return errors.Wrap(cmd.Run(), "error opening page in browser")
}
func fetchIDToken(oc oidcConfig) (*idTokenResult, error) {
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, oc.Provider)
if err != nil {
return nil, errors.Wrap(err, "error creating oidc provider")
}
redirectURL := "http://localhost:9999/code"
// Configure an OpenID Connect aware OAuth2 client.
oauth2Config := oauth2.Config{
ClientID: oc.ClientID,
ClientSecret: oc.ClientSecret,
RedirectURL: redirectURL,
// Discovery returns the OAuth2 endpoints.
Endpoint: provider.Endpoint(),
// "openid" is a required scope for OpenID Connect flows.
Scopes: []string{oidc.ScopeOpenID, "email"},
}
var rawState [40]byte
_, err = rand.Read(rawState[:])
if err != nil {
return nil, errors.Wrap(err, "error generating oauth state")
}
state := hex.EncodeToString(rawState[:])
url := oauth2Config.AuthCodeURL(state,
oauth2.SetAuthURLParam("hd", oc.HostedDomain),
// If this is set, or if the user actually needs to
// authenticate, we aren't able to automatically close the
// browser window after authentication :(
// oauth2.SetAuthURLParam("prompt", "consent")
)
if err := openInBrowser(url); err != nil {
return nil, err
}
server := http.Server{
Addr: ":9999",
}
server.SetKeepAlivesEnabled(false)
requestSignal := make(chan idTokenMessage)
serverSignal := make(chan idTokenMessage)
server.Handler = handleOAuth2Callback(provider, oauth2Config, state, requestSignal)
go func() {
result := <-requestSignal
err := server.Shutdown(ctx)
if err != nil {
result = idTokenMessage{
err: errors.Wrap(err, "error on server shutdown"),
}
}
serverSignal <- result
}()
err = server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
return nil, errors.Wrap(err, "error from server.ListenAndServe")
}
result := <-serverSignal
if result.err != nil {
return nil, err
}
return &result.result, nil
}
func writeError(w http.ResponseWriter, err error, msg string) error {
if err == nil {
err = errors.New(msg)
} else {
err = errors.Wrap(err, msg)
}
w.WriteHeader(500)
writeString(w, fmt.Sprintf("%v", err))
return err
}
func handleOAuth2Callback(provider *oidc.Provider, oauth2Config oauth2.Config, state string, signal chan idTokenMessage) http.HandlerFunc {
verifier := provider.Verifier(&oidc.Config{ClientID: oauth2Config.ClientID})
return func(w http.ResponseWriter, r *http.Request) {
// Verify request state matches response state
reqState := r.URL.Query().Get("state")
if reqState != state {
signal <- idTokenMessage{err: writeError(w, nil, "response state does not match request state")}
return
}
// Exchange authorisation code for access/id token
oauth2Token, err := oauth2Config.Exchange(r.Context(), r.URL.Query().Get("code"))
if err != nil {
signal <- idTokenMessage{err: writeError(w, err, "error exchanging authorisation code for access/id tokens")}
return
}
// Extract ID Token from OAuth2 token.
rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok {
signal <- idTokenMessage{err: writeError(w, nil, "no id_token included when fetching access token")}
return
}
// Parse and verify ID Token payload.
idToken, err := verifier.Verify(r.Context(), rawIDToken)
if err != nil {
signal <- idTokenMessage{err: writeError(w, err, "error verifying id token")}
return
}
// Extract custom claim
var claims struct {
Email string `json:"email"`
Subject string `json:"sub"`
}
err = idToken.Claims(&claims)
if err != nil {
signal <- idTokenMessage{err: writeError(w, err, "error extracting claims from id token")}
return
}
// Pass result back
signal <- idTokenMessage{
result: idTokenResult{
RawToken: rawIDToken,
Token: idToken,
Email: claims.Email,
Sub: claims.Subject,
},
}
// Close the browser window
writeString(w, "<script>window.close()</script>")
}
}
func writeString(w http.ResponseWriter, s string) {
// <link> is to prevent browsers trying to load a favicon for this page
w.Write([]byte(`<!DOCTYPE html><html><link rel="icon" href="data:;base64,iVBORw0KGgo="><body>` + s))
}