-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgoogle_openid.go
253 lines (218 loc) · 7.51 KB
/
google_openid.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
package auth
import (
"context"
"fmt"
"net/http"
"time"
"github.com/fatih/color"
"github.com/coreos/go-oidc"
protocol "github.com/gjbae1212/grpc-vpn/grpc/go"
"github.com/gjbae1212/grpc-vpn/internal"
"github.com/pkg/browser"
"github.com/pkg/errors"
"golang.org/x/oauth2"
"google.golang.org/grpc"
)
// Only Support Redirect URL http://localhost:10000/code
const (
googleOpenIDProvider = "https://accounts.google.com"
redirectServer = "http://localhost:10000"
redirectPath = "/code"
redirectPort = "10000"
redirectURL = "http://localhost:10000/code"
)
// https://developers.google.com/identity/protocols/oauth2/native-app
// https://developers.google.com/identity/protocols/oauth2/openid-connect
type GoogleOpenIDConfig struct {
ClientId string // google client id
ClientSecret string // google secret
HD string // gsuite domain (only vpn-server)
AllowEmails []string // allow emails (only vpn-server)
}
// ServerAuth returns ServerAuthMethod and bool value(whether exist or not).
func (c *GoogleOpenIDConfig) ServerAuth() (ServerAuthMethod, bool) {
if c.ClientId == "" || c.ClientSecret == "" {
return nil, false
}
return ServerAuthMethod(c.unaryServerInterceptor()), true
}
// ClientAuth is returns ClientAuthMethod for Google Open ID.
func (c *GoogleOpenIDConfig) ClientAuth() (ClientAuthMethod, bool) {
if c.ClientId == "" || c.ClientSecret == "" {
return nil, false
}
return c.clientAuthMethod(), true
}
// unaryServerInterceptor returns new unary server interceptor that checks an authorization with google openID.
func (c *GoogleOpenIDConfig) unaryServerInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
auth, ok := req.(*protocol.AuthRequest)
if !ok {
return handler(ctx, req)
}
if auth.AuthType != protocol.AuthType_AT_GOOGLE_OPEN_ID {
return handler(ctx, req)
}
if auth.GoogleOpenId.Code == "" {
return nil, internal.ErrorUnauthorized
}
clientID := c.ClientId
clientSecret := c.ClientSecret
hd := c.HD
allowEmails := c.AllowEmails
provider, err := oidc.NewProvider(context.Background(), googleOpenIDProvider)
if err != nil {
return nil, internal.ErrorUnknown
}
oauthConf := oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
exCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
token, err := oauthConf.Exchange(exCtx, auth.GoogleOpenId.Code)
if err != nil {
return nil, internal.ErrorUnauthorized
}
expiresIn := token.Extra("expires_in").(float64)
if expiresIn <= 10 { // Fail when remaining lifetime is less than 10 seconds.
return nil, internal.ErrorUnauthorized
}
rawIdToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, internal.ErrorUnauthorized
}
idToken, err := provider.Verifier(&oidc.Config{ClientID: clientID}).Verify(ctx, rawIdToken)
if err != nil {
return nil, internal.ErrorUnauthorized
}
claims := map[string]interface{}{}
if err := idToken.Claims(&claims); err != nil {
return nil, internal.ErrorUnauthorized
}
// check gsuite domain(matched)
// if hd is empty, don't check hd
if hd != "" {
if claims["hd"] == nil || hd != claims["hd"].(string) {
return nil, internal.ErrorUnauthorized
}
}
// check email
// if allowEmails is empty, don't check email
if len(allowEmails) != 0 {
if !internal.IsMatchedStringFromSlice(claims["email"].(string), allowEmails) {
return nil, internal.ErrorUnauthorized
}
}
// inject user
newCtx := context.WithValue(ctx, UserCtxName, claims["email"].(string))
return handler(newCtx, req)
}
}
// ClientAuthMethod returns auth method for client.
func (c *GoogleOpenIDConfig) clientAuthMethod() ClientAuthMethod {
return func(conn protocol.VPNClient) (jwt string, err error) {
if conn == nil {
return "", errors.Wrapf(internal.ErrorInvalidParams, "Google OpenID ClientAuthMethod")
}
// extract information for oauth2
clientID := c.ClientId
clientSecret := c.ClientSecret
if clientID == "" || clientSecret == "" {
return "", errors.Wrapf(internal.ErrorInvalidParams, "Google OpenID ClientAuthMethod")
}
provider, err := oidc.NewProvider(context.Background(), googleOpenIDProvider)
if err != nil {
return "", errors.Wrapf(err, "Google OpenID ClientAuthMethod")
}
// start http server
serverCtx, cancel := context.WithCancel(context.Background())
defer cancel()
var code string
mux := http.NewServeMux()
server := http.Server{Addr: fmt.Sprintf(":%s", redirectPort), Handler: mux}
mux.HandleFunc(redirectPath, func(w http.ResponseWriter, req *http.Request) {
// extract code
if req.URL.Query()["code"] != nil && len(req.URL.Query()["code"]) > 0 {
code = req.URL.Query()["code"][0]
http.Redirect(w, req, redirectServer+"/success", 301)
} else {
http.Redirect(w, req, redirectServer+"/fail", 301)
}
})
mux.HandleFunc("/success", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("[REDIRECT] Close this page."))
cancel()
})
mux.HandleFunc("/fail", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("[REDIRECT] Close this page."))
cancel()
})
go func() {
server.ListenAndServe()
}()
state := internal.GenerateRandomString(10)
conf := oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
if err := browser.OpenURL(conf.AuthCodeURL(state)); err != nil {
return "", errors.Wrapf(err, "Google OpenID ClientAuthMethod")
}
fmt.Println(color.GreenString("[WAIT] YOUR GOOGLE OPENID AUTHENTICATION"))
select {
case <-serverCtx.Done():
server.Shutdown(serverCtx)
}
if code == "" {
return "", errors.Wrapf(internal.ErrorUnauthorized, "Google OpenID ClientAuthMethod")
}
// call authentication request to VPN server.
authCtx, authCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer authCancel()
response, err := conn.Auth(authCtx, &protocol.AuthRequest{
AuthType: protocol.AuthType_AT_GOOGLE_OPEN_ID,
GoogleOpenId: &protocol.AuthRequest_GoogleOpenID{
Code: code,
},
})
if err != nil {
return "", errors.Wrapf(internal.ErrorUnauthorized, "Google OpenID ClientAuthMethod")
}
if response.ErrorCode != protocol.ErrorCode_EC_SUCCESS || response.Jwt == "" {
return "", errors.Wrapf(internal.ErrorUnauthorized, "Google OpenID ClientAuthMethod")
}
return response.Jwt, nil
}
}
// NewServerManagerForGoogleOpenID returns ServerManager implementing googleOpenI
func NewServerManagerForGoogleOpenID(clientId, clientSecret, hd string, allowEmails []string) (ServerManager, error) {
if clientId == "" || clientSecret == "" {
return nil, internal.ErrorInvalidParams
}
if allowEmails == nil {
allowEmails = []string{}
}
return &GoogleOpenIDConfig{
ClientId: clientId,
ClientSecret: clientSecret,
HD: hd,
AllowEmails: allowEmails,
}, nil
}
// NewClientManagerForGoogleOpenID returns ClientManager implementing googleOpenId.
func NewClientManagerForGoogleOpenID(clientId, clientSecret string) (ClientManager, error) {
if clientId == "" || clientSecret == "" {
return nil, internal.ErrorInvalidParams
}
return &GoogleOpenIDConfig{
ClientId: clientId,
ClientSecret: clientSecret,
}, nil
}