git.iko.soy/typeable/oauth2-proxy
on request-rules help sign in
294 lines 8.9 kB history raw
1package providers
3import (
4 "bytes"
5 "context"
6 "encoding/base64"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io"
11 "io/ioutil"
12 "net/url"
13 "strings"
14 "time"
16 "github.com/oauth2-proxy/oauth2-proxy/pkg/apis/sessions"
17 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
18 "github.com/oauth2-proxy/oauth2-proxy/pkg/requests"
19 "golang.org/x/oauth2/google"
20 admin "google.golang.org/api/admin/directory/v1"
21 "google.golang.org/api/googleapi"
22 "google.golang.org/api/option"
25// GoogleProvider represents an Google based Identity Provider
26type GoogleProvider struct {
27 *ProviderData
28 RedeemRefreshURL *url.URL
29 // GroupValidator is a function that determines if the passed email is in
30 // the configured Google group.
31 GroupValidator func(string) bool
34var _ Provider = (*GoogleProvider)(nil)
36type claims struct {
37 Subject string `json:"sub"`
38 Email string `json:"email"`
39 EmailVerified bool `json:"email_verified"`
42// NewGoogleProvider initiates a new GoogleProvider
43func NewGoogleProvider(p *ProviderData) *GoogleProvider {
44 p.ProviderName = "Google"
45 if p.LoginURL.String() == "" {
46 p.LoginURL = &url.URL{Scheme: "https",
47 Host: "accounts.google.com",
48 Path: "/o/oauth2/auth",
49 // to get a refresh token. see https://developers.google.com/identity/protocols/OAuth2WebServer#offline
50 RawQuery: "access_type=offline",
51 }
52 }
53 if p.RedeemURL.String() == "" {
54 p.RedeemURL = &url.URL{Scheme: "https",
55 Host: "www.googleapis.com",
56 Path: "/oauth2/v3/token"}
57 }
58 if p.ValidateURL.String() == "" {
59 p.ValidateURL = &url.URL{Scheme: "https",
60 Host: "www.googleapis.com",
61 Path: "/oauth2/v1/tokeninfo"}
62 }
63 if p.Scope == "" {
64 p.Scope = "profile email"
65 }
67 return &GoogleProvider{
68 ProviderData: p,
69 // Set a default GroupValidator to just always return valid (true), it will
70 // be overwritten if we configured a Google group restriction.
71 GroupValidator: func(email string) bool {
72 return true
73 },
74 }
77func claimsFromIDToken(idToken string) (*claims, error) {
79 // id_token is a base64 encode ID token payload
80 // https://developers.google.com/accounts/docs/OAuth2Login#obtainuserinfo
81 jwt := strings.Split(idToken, ".")
82 jwtData := strings.TrimSuffix(jwt[1], "=")
83 b, err := base64.RawURLEncoding.DecodeString(jwtData)
84 if err != nil {
85 return nil, err
86 }
88 c := &claims{}
89 err = json.Unmarshal(b, c)
90 if err != nil {
91 return nil, err
92 }
93 if c.Email == "" {
94 return nil, errors.New("missing email")
95 }
96 if !c.EmailVerified {
97 return nil, fmt.Errorf("email %s not listed as verified", c.Email)
98 }
99 return c, nil
102// Redeem exchanges the OAuth2 authentication token for an ID token
103func (p *GoogleProvider) Redeem(ctx context.Context, redirectURL, code string) (s *sessions.SessionState, err error) {
104 if code == "" {
105 err = errors.New("missing code")
106 return
107 }
108 clientSecret, err := p.GetClientSecret()
109 if err != nil {
110 return
111 }
113 params := url.Values{}
114 params.Add("redirect_uri", redirectURL)
115 params.Add("client_id", p.ClientID)
116 params.Add("client_secret", clientSecret)
117 params.Add("code", code)
118 params.Add("grant_type", "authorization_code")
120 var jsonResponse struct {
121 AccessToken string `json:"access_token"`
122 RefreshToken string `json:"refresh_token"`
123 ExpiresIn int64 `json:"expires_in"`
124 IDToken string `json:"id_token"`
125 }
127 err = requests.New(p.RedeemURL.String()).
128 WithContext(ctx).
129 WithMethod("POST").
130 WithBody(bytes.NewBufferString(params.Encode())).
131 SetHeader("Content-Type", "application/x-www-form-urlencoded").
132 Do().
133 UnmarshalInto(&jsonResponse)
134 if err != nil {
135 return nil, err
136 }
138 c, err := claimsFromIDToken(jsonResponse.IDToken)
139 if err != nil {
140 return
141 }
143 created := time.Now()
144 expires := time.Now().Add(time.Duration(jsonResponse.ExpiresIn) * time.Second).Truncate(time.Second)
145 s = &sessions.SessionState{
146 AccessToken: jsonResponse.AccessToken,
147 IDToken: jsonResponse.IDToken,
148 CreatedAt: &created,
149 ExpiresOn: &expires,
150 RefreshToken: jsonResponse.RefreshToken,
151 Email: c.Email,
152 User: c.Subject,
153 }
154 return
157// SetGroupRestriction configures the GoogleProvider to restrict access to the
158// specified group(s). AdminEmail has to be an administrative email on the domain that is
159// checked. CredentialsFile is the path to a json file containing a Google service
160// account credentials.
161func (p *GoogleProvider) SetGroupRestriction(groups []string, adminEmail string, credentialsReader io.Reader) {
162 adminService := getAdminService(adminEmail, credentialsReader)
163 p.GroupValidator = func(email string) bool {
164 return userInGroup(adminService, groups, email)
165 }
168func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Service {
169 data, err := ioutil.ReadAll(credentialsReader)
170 if err != nil {
171 logger.Fatal("can't read Google credentials file:", err)
172 }
173 conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
174 if err != nil {
175 logger.Fatal("can't load Google credentials file:", err)
176 }
177 conf.Subject = adminEmail
179 ctx := context.Background()
180 client := conf.Client(ctx)
181 adminService, err := admin.NewService(ctx, option.WithHTTPClient(client))
182 if err != nil {
183 logger.Fatal(err)
184 }
185 return adminService
188func userInGroup(service *admin.Service, groups []string, email string) bool {
189 for _, group := range groups {
190 // Use the HasMember API to checking for the user's presence in each group or nested subgroups
191 req := service.Members.HasMember(group, email)
192 r, err := req.Do()
193 if err != nil {
194 gerr, ok := err.(*googleapi.Error)
195 switch {
196 case ok && gerr.Code == 404:
197 logger.Printf("error checking membership in group %s: group does not exist", group)
198 case ok && gerr.Code == 400:
199 // It is possible for Members.HasMember to return false even if the email is a group member.
200 // One case that can cause this is if the user email is from a different domain than the group,
201 // e.g. "member@otherdomain.com" in the group "group@mydomain.com" will result in a 400 error
202 // from the HasMember API. In that case, attempt to query the member object directly from the group.
203 req := service.Members.Get(group, email)
204 r, err := req.Do()
206 if err != nil {
207 logger.Printf("error using get API to check member %s of google group %s: user not in the group", email, group)
208 continue
209 }
211 // If the non-domain user is found within the group, still verify that they are "ACTIVE".
212 // Do not count the user as belonging to a group if they have another status ("ARCHIVED", "SUSPENDED", or "UNKNOWN").
213 if r.Status == "ACTIVE" {
214 return true
215 }
216 default:
217 logger.Printf("error checking group membership: %v", err)
218 }
219 continue
220 }
221 if r.IsMember {
222 return true
223 }
224 }
225 return false
228// ValidateGroup validates that the provided email exists in the configured Google
229// group(s).
230func (p *GoogleProvider) ValidateGroup(email string) bool {
231 return p.GroupValidator(email)
234// RefreshSessionIfNeeded checks if the session has expired and uses the
235// RefreshToken to fetch a new ID token if required
236func (p *GoogleProvider) RefreshSessionIfNeeded(ctx context.Context, s *sessions.SessionState) (bool, error) {
237 if s == nil || (s.ExpiresOn != nil && s.ExpiresOn.After(time.Now())) || s.RefreshToken == "" {
238 return false, nil
239 }
241 newToken, newIDToken, duration, err := p.redeemRefreshToken(ctx, s.RefreshToken)
242 if err != nil {
243 return false, err
244 }
246 // re-check that the user is in the proper google group(s)
247 if !p.ValidateGroup(s.Email) {
248 return false, fmt.Errorf("%s is no longer in the group(s)", s.Email)
249 }
251 origExpiration := s.ExpiresOn
252 expires := time.Now().Add(duration).Truncate(time.Second)
253 s.AccessToken = newToken
254 s.IDToken = newIDToken
255 s.ExpiresOn = &expires
256 logger.Printf("refreshed access token %s (expired on %s)", s, origExpiration)
257 return true, nil
260func (p *GoogleProvider) redeemRefreshToken(ctx context.Context, refreshToken string) (token string, idToken string, expires time.Duration, err error) {
261 // https://developers.google.com/identity/protocols/OAuth2WebServer#refresh
262 clientSecret, err := p.GetClientSecret()
263 if err != nil {
264 return
265 }
267 params := url.Values{}
268 params.Add("client_id", p.ClientID)
269 params.Add("client_secret", clientSecret)
270 params.Add("refresh_token", refreshToken)
271 params.Add("grant_type", "refresh_token")
273 var data struct {
274 AccessToken string `json:"access_token"`
275 ExpiresIn int64 `json:"expires_in"`
276 IDToken string `json:"id_token"`
277 }
279 err = requests.New(p.RedeemURL.String()).
280 WithContext(ctx).
281 WithMethod("POST").
282 WithBody(bytes.NewBufferString(params.Encode())).
283 SetHeader("Content-Type", "application/x-www-form-urlencoded").
284 Do().
285 UnmarshalInto(&data)
286 if err != nil {
287 return "", "", 0, err
288 }
290 token = data.AccessToken
291 idToken = data.IDToken
292 expires = time.Duration(data.ExpiresIn) * time.Second
293 return