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 {
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)
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",
53 if p.RedeemURL.String() == "" {
54 p.RedeemURL = &url.URL{Scheme: "https",
55 Host: "www.googleapis.com",
56 Path: "/oauth2/v3/token"}
58 if p.ValidateURL.String() == "" {
59 p.ValidateURL = &url.URL{Scheme: "https",
60 Host: "www.googleapis.com",
61 Path: "/oauth2/v1/tokeninfo"}
64 p.Scope = "profile email"
67 return &GoogleProvider{
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 {
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)
89 err = json.Unmarshal(b, c)
94 return nil, errors.New("missing email")
97 return nil, fmt.Errorf("email %s not listed as verified", c.Email)
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) {
105 err = errors.New("missing code")
108 clientSecret, err := p.GetClientSecret()
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"`
127 err = requests.New(p.RedeemURL.String()).
130 WithBody(bytes.NewBufferString(params.Encode())).
131 SetHeader("Content-Type", "application/x-www-form-urlencoded").
133 UnmarshalInto(&jsonResponse)
138 c, err := claimsFromIDToken(jsonResponse.IDToken)
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,
150 RefreshToken: jsonResponse.RefreshToken,
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)
168func getAdminService(adminEmail string, credentialsReader io.Reader) *admin.Service {
169 data, err := ioutil.ReadAll(credentialsReader)
171 logger.Fatal("can't read Google credentials file:", err)
173 conf, err := google.JWTConfigFromJSON(data, admin.AdminDirectoryUserReadonlyScope, admin.AdminDirectoryGroupReadonlyScope)
175 logger.Fatal("can't load Google credentials file:", err)
177 conf.Subject = adminEmail
179 ctx := context.Background()
180 client := conf.Client(ctx)
181 adminService, err := admin.NewService(ctx, option.WithHTTPClient(client))
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)
194 gerr, ok := err.(*googleapi.Error)
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)
207 logger.Printf("error using get API to check member %s of google group %s: user not in the group", email, group)
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" {
217 logger.Printf("error checking group membership: %v", err)
228// ValidateGroup validates that the provided email exists in the configured Google
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 == "" {
241 newToken, newIDToken, duration, err := p.redeemRefreshToken(ctx, s.RefreshToken)
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)
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)
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()
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")
274 AccessToken string `json:"access_token"`
275 ExpiresIn int64 `json:"expires_in"`
276 IDToken string `json:"id_token"`
279 err = requests.New(p.RedeemURL.String()).
282 WithBody(bytes.NewBufferString(params.Encode())).
283 SetHeader("Content-Type", "application/x-www-form-urlencoded").
287 return "", "", 0, err
290 token = data.AccessToken
291 idToken = data.IDToken
292 expires = time.Duration(data.ExpiresIn) * time.Second
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list