20 "github.com/coreos/go-oidc"
21 "github.com/mbland/hmacauth"
22 sessionsapi "github.com/pusher/oauth2_proxy/pkg/apis/sessions"
23 "github.com/pusher/oauth2_proxy/pkg/cookies"
24 "github.com/pusher/oauth2_proxy/pkg/encryption"
25 "github.com/pusher/oauth2_proxy/pkg/logger"
26 "github.com/pusher/oauth2_proxy/providers"
27 "github.com/yhat/wsutil"
31 // SignatureHeader is the name of the request header containing the GAP Signature
33 SignatureHeader = "GAP-Signature"
38 applicationJSON = "application/json"
41// SignatureHeaders contains the headers to be signed by the hmac algorithm
43var SignatureHeaders = []string{
51 "X-Forwarded-Preferred-User",
52 "X-Forwarded-Access-Token",
58 // ErrNeedsLogin means the user should be redirected to the login page
59 ErrNeedsLogin = errors.New("redirect to login page")
61 // Used to check final redirects are not susceptible to open redirects.
62 // Matches //, /\ and both of these with whitespace in between (eg / / or / \).
63 invalidRedirectRegex = regexp.MustCompile(`^/(\s|\v)?(/|\\)`)
66// OAuthProxy is the main authentication proxy
67type OAuthProxy struct {
75 CookieExpire time.Duration
76 CookieRefresh time.Duration
78 Validator func(string) bool
85 OAuthCallbackPath string
89 redirectURL *url.URL // the url to receive requests at
90 whitelistDomains []string
91 provider providers.Provider
92 providerNameOverride string
93 sessionStore sessionsapi.SessionStore
96 HtpasswdFile *HtpasswdFile
97 DisplayHtpasswdForm bool
101 SkipProviderButton bool
103 BasicAuthPassword string
105 SetAuthorization bool
106 PassAuthorization bool
107 PreferEmailToUser bool
108 skipAuthRegex []string
109 skipAuthPreflight bool
110 skipJwtBearerTokens bool
111 jwtBearerVerifiers []*oidc.IDTokenVerifier
112 compiledRegex []*regexp.Regexp
113 templates *template.Template
118// UpstreamProxy represents an upstream server to proxy to
119type UpstreamProxy struct {
122 wsHandler http.Handler
123 auth hmacauth.HmacAuth
126// ServeHTTP proxies requests to the upstream provider while signing the
128func (u *UpstreamProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
129 w.Header().Set("GAP-Upstream-Address", u.upstream)
131 r.Header.Set("GAP-Auth", w.Header().Get("GAP-Auth"))
132 u.auth.SignRequest(r)
134 if u.wsHandler != nil && strings.EqualFold(r.Header.Get("Connection"), "upgrade") && r.Header.Get("Upgrade") == "websocket" {
135 u.wsHandler.ServeHTTP(w, r)
137 u.handler.ServeHTTP(w, r)
142// NewReverseProxy creates a new reverse proxy for proxying requests to upstream
144func NewReverseProxy(target *url.URL, opts *Options) (proxy *httputil.ReverseProxy) {
145 proxy = httputil.NewSingleHostReverseProxy(target)
146 proxy.FlushInterval = opts.FlushInterval
147 if opts.SSLUpstreamInsecureSkipVerify {
148 proxy.Transport = &http.Transport{
149 TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
155func setProxyUpstreamHostHeader(proxy *httputil.ReverseProxy, target *url.URL) {
156 director := proxy.Director
157 proxy.Director = func(req *http.Request) {
159 // use RequestURI so that we aren't unescaping encoded slashes in the request path
160 req.Host = target.Host
161 req.URL.Opaque = req.RequestURI
162 req.URL.RawQuery = ""
166func setProxyDirector(proxy *httputil.ReverseProxy) {
167 director := proxy.Director
168 proxy.Director = func(req *http.Request) {
170 // use RequestURI so that we aren't unescaping encoded slashes in the request path
171 req.URL.Opaque = req.RequestURI
172 req.URL.RawQuery = ""
176// NewFileServer creates a http.Handler to serve files from the filesystem
177func NewFileServer(path string, filesystemPath string) (proxy http.Handler) {
178 return http.StripPrefix(path, http.FileServer(http.Dir(filesystemPath)))
181// NewWebSocketOrRestReverseProxy creates a reverse proxy for REST or websocket based on url
182func NewWebSocketOrRestReverseProxy(u *url.URL, opts *Options, auth hmacauth.HmacAuth) http.Handler {
184 proxy := NewReverseProxy(u, opts)
185 if !opts.PassHostHeader {
186 setProxyUpstreamHostHeader(proxy, u)
188 setProxyDirector(proxy)
191 // this should give us a wss:// scheme if the url is https:// based.
192 var wsProxy *wsutil.ReverseProxy
193 if opts.ProxyWebSockets {
194 wsScheme := "ws" + strings.TrimPrefix(u.Scheme, "http")
195 wsURL := &url.URL{Scheme: wsScheme, Host: u.Host}
196 wsProxy = wsutil.NewSingleHostReverseProxy(wsURL)
198 return &UpstreamProxy{
206// NewOAuthProxy creates a new instance of OAuthProxy from the options provided
207func NewOAuthProxy(opts *Options, validator func(string) bool) *OAuthProxy {
208 serveMux := http.NewServeMux()
209 var auth hmacauth.HmacAuth
210 if sigData := opts.signatureData; sigData != nil {
211 auth = hmacauth.NewHmacAuth(sigData.hash, []byte(sigData.key),
212 SignatureHeader, SignatureHeaders)
214 for _, u := range opts.proxyURLs {
218 case httpScheme, httpsScheme:
219 logger.Printf("mapping path %q => upstream %q", path, u)
220 proxy := NewWebSocketOrRestReverseProxy(u, opts, auth)
221 serveMux.Handle(path, proxy)
223 responseCode, err := strconv.Atoi(host)
225 logger.Printf("unable to convert %q to int, use default \"200\"", host)
229 serveMux.HandleFunc(path, func(rw http.ResponseWriter, req *http.Request) {
230 rw.WriteHeader(responseCode)
231 fmt.Fprintf(rw, "Authenticated")
234 if u.Fragment != "" {
237 logger.Printf("mapping path %q => file system %q", path, u.Path)
238 proxy := NewFileServer(path, u.Path)
239 uProxy := UpstreamProxy{
245 serveMux.Handle(path, &uProxy)
247 panic(fmt.Sprintf("unknown upstream protocol %s", u.Scheme))
250 for _, u := range opts.CompiledRegex {
251 logger.Printf("compiled skip-auth-regex => %q", u)
254 if opts.SkipJwtBearerTokens {
255 logger.Printf("Skipping JWT tokens from configured OIDC issuer: %q", opts.OIDCIssuerURL)
256 for _, issuer := range opts.ExtraJwtIssuers {
257 logger.Printf("Skipping JWT tokens from extra JWT issuer: %q", issuer)
260 redirectURL := opts.redirectURL
261 if redirectURL.Path == "" {
262 redirectURL.Path = fmt.Sprintf("%s/callback", opts.ProxyPrefix)
265 logger.Printf("OAuthProxy configured for %s Client ID: %s", opts.provider.Data().ProviderName, opts.ClientID)
266 refresh := "disabled"
267 if opts.CookieRefresh != time.Duration(0) {
268 refresh = fmt.Sprintf("after %s", opts.CookieRefresh)
271 logger.Printf("Cookie settings: name:%s secure(https):%v httponly:%v expiry:%s domain:%s path:%s samesite:%s refresh:%s", opts.CookieName, opts.CookieSecure, opts.CookieHTTPOnly, opts.CookieExpire, opts.CookieDomain, opts.CookiePath, opts.CookieSameSite, refresh)
274 CookieName: opts.CookieName,
275 CSRFCookieName: fmt.Sprintf("%v_%v", opts.CookieName, "csrf"),
276 CookieSeed: opts.CookieSecret,
277 CookieDomain: opts.CookieDomain,
278 CookiePath: opts.CookiePath,
279 CookieSecure: opts.CookieSecure,
280 CookieHTTPOnly: opts.CookieHTTPOnly,
281 CookieExpire: opts.CookieExpire,
282 CookieRefresh: opts.CookieRefresh,
283 CookieSameSite: opts.CookieSameSite,
284 Validator: validator,
286 RobotsPath: "/robots.txt",
287 PingPath: opts.PingPath,
288 SignInPath: fmt.Sprintf("%s/sign_in", opts.ProxyPrefix),
289 SignOutPath: fmt.Sprintf("%s/sign_out", opts.ProxyPrefix),
290 OAuthStartPath: fmt.Sprintf("%s/start", opts.ProxyPrefix),
291 OAuthCallbackPath: fmt.Sprintf("%s/callback", opts.ProxyPrefix),
292 AuthOnlyPath: fmt.Sprintf("%s/auth", opts.ProxyPrefix),
293 UserInfoPath: fmt.Sprintf("%s/userinfo", opts.ProxyPrefix),
295 ProxyPrefix: opts.ProxyPrefix,
296 provider: opts.provider,
297 providerNameOverride: opts.ProviderName,
298 sessionStore: opts.sessionStore,
300 redirectURL: redirectURL,
301 whitelistDomains: opts.WhitelistDomains,
302 skipAuthRegex: opts.SkipAuthRegex,
303 skipAuthPreflight: opts.SkipAuthPreflight,
304 skipJwtBearerTokens: opts.SkipJwtBearerTokens,
305 jwtBearerVerifiers: opts.jwtBearerVerifiers,
306 compiledRegex: opts.CompiledRegex,
307 SetXAuthRequest: opts.SetXAuthRequest,
308 PassBasicAuth: opts.PassBasicAuth,
309 PassUserHeaders: opts.PassUserHeaders,
310 BasicAuthPassword: opts.BasicAuthPassword,
311 PassAccessToken: opts.PassAccessToken,
312 SetAuthorization: opts.SetAuthorization,
313 PassAuthorization: opts.PassAuthorization,
314 PreferEmailToUser: opts.PreferEmailToUser,
315 SkipProviderButton: opts.SkipProviderButton,
316 templates: loadTemplates(opts.CustomTemplatesDir),
322// GetRedirectURI returns the redirectURL that the upstream OAuth Provider will
323// redirect clients to once authenticated
324func (p *OAuthProxy) GetRedirectURI(host string) string {
325 // default to the request Host if not set
326 if p.redirectURL.Host != "" {
327 return p.redirectURL.String()
333 u.Scheme = httpsScheme
335 u.Scheme = httpScheme
342func (p *OAuthProxy) displayCustomLoginForm() bool {
343 return p.HtpasswdFile != nil && p.DisplayHtpasswdForm
346func (p *OAuthProxy) redeemCode(host, code string) (s *sessionsapi.SessionState, err error) {
348 return nil, errors.New("missing code")
350 redirectURI := p.GetRedirectURI(host)
351 s, err = p.provider.Redeem(redirectURI, code)
357 s.Email, err = p.provider.GetEmailAddress(s)
360 if s.PreferredUsername == "" {
361 s.PreferredUsername, err = p.provider.GetPreferredUsername(s)
362 if err != nil && err.Error() == "not implemented" {
368 s.User, err = p.provider.GetUserName(s)
369 if err != nil && err.Error() == "not implemented" {
376// MakeCSRFCookie creates a cookie for CSRF
377func (p *OAuthProxy) MakeCSRFCookie(req *http.Request, value string, expiration time.Duration, now time.Time) *http.Cookie {
378 return p.makeCookie(req, p.CSRFCookieName, value, expiration, now)
381func (p *OAuthProxy) makeCookie(req *http.Request, name string, value string, expiration time.Duration, now time.Time) *http.Cookie {
382 if p.CookieDomain != "" {
384 if h, _, err := net.SplitHostPort(domain); err == nil {
387 if !strings.HasSuffix(domain, p.CookieDomain) {
388 logger.Printf("Warning: request host is %q but using configured cookie domain of %q", domain, p.CookieDomain)
396 Domain: p.CookieDomain,
397 HttpOnly: p.CookieHTTPOnly,
398 Secure: p.CookieSecure,
399 Expires: now.Add(expiration),
400 SameSite: cookies.ParseSameSite(p.CookieSameSite),
404// ClearCSRFCookie creates a cookie to unset the CSRF cookie stored in the user's
406func (p *OAuthProxy) ClearCSRFCookie(rw http.ResponseWriter, req *http.Request) {
407 http.SetCookie(rw, p.MakeCSRFCookie(req, "", time.Hour*-1, time.Now()))
410// SetCSRFCookie adds a CSRF cookie to the response
411func (p *OAuthProxy) SetCSRFCookie(rw http.ResponseWriter, req *http.Request, val string) {
412 http.SetCookie(rw, p.MakeCSRFCookie(req, val, p.CookieExpire, time.Now()))
415// ClearSessionCookie creates a cookie to unset the user's authentication cookie
416// stored in the user's session
417func (p *OAuthProxy) ClearSessionCookie(rw http.ResponseWriter, req *http.Request) error {
418 return p.sessionStore.Clear(rw, req)
421// LoadCookiedSession reads the user's authentication details from the request
422func (p *OAuthProxy) LoadCookiedSession(req *http.Request) (*sessionsapi.SessionState, error) {
423 return p.sessionStore.Load(req)
426// SaveSession creates a new session cookie value and sets this on the response
427func (p *OAuthProxy) SaveSession(rw http.ResponseWriter, req *http.Request, s *sessionsapi.SessionState) error {
428 return p.sessionStore.Save(rw, req, s)
431// RobotsTxt disallows scraping pages from the OAuthProxy
432func (p *OAuthProxy) RobotsTxt(rw http.ResponseWriter) {
433 rw.WriteHeader(http.StatusOK)
434 fmt.Fprintf(rw, "User-agent: *\nDisallow: /")
437// PingPage responds 200 OK to requests
438func (p *OAuthProxy) PingPage(rw http.ResponseWriter) {
439 rw.WriteHeader(http.StatusOK)
440 fmt.Fprintf(rw, "OK")
443// ErrorPage writes an error response
444func (p *OAuthProxy) ErrorPage(rw http.ResponseWriter, code int, title string, message string) {
451 Title: fmt.Sprintf("%d %s", code, title),
453 ProxyPrefix: p.ProxyPrefix,
455 p.templates.ExecuteTemplate(rw, "error.html", t)
458// SignInPage writes the sing in template to the response
459func (p *OAuthProxy) SignInPage(rw http.ResponseWriter, req *http.Request, code int) {
460 p.ClearSessionCookie(rw, req)
463 redirectURL, err := p.GetRedirect(req)
465 logger.Printf("Error obtaining redirect: %s", err.Error())
466 p.ErrorPage(rw, 500, "Internal Error", err.Error())
470 if redirectURL == p.SignInPath {
483 ProviderName: p.provider.Data().ProviderName,
484 SignInMessage: p.SignInMessage,
485 CustomLogin: p.displayCustomLoginForm(),
486 Redirect: redirectURL,
488 ProxyPrefix: p.ProxyPrefix,
489 Footer: template.HTML(p.Footer),
491 if p.providerNameOverride != "" {
492 t.ProviderName = p.providerNameOverride
494 p.templates.ExecuteTemplate(rw, "sign_in.html", t)
497// ManualSignIn handles basic auth logins to the proxy
498func (p *OAuthProxy) ManualSignIn(rw http.ResponseWriter, req *http.Request) (string, bool) {
499 if req.Method != "POST" || p.HtpasswdFile == nil {
502 user := req.FormValue("username")
503 passwd := req.FormValue("password")
508 if p.HtpasswdFile.Validate(user, passwd) {
509 logger.PrintAuthf(user, req, logger.AuthSuccess, "Authenticated via HtpasswdFile")
512 logger.PrintAuthf(user, req, logger.AuthFailure, "Invalid authentication via HtpasswdFile")
516// GetRedirect reads the query parameter to get the URL to redirect clients to
517// once authenticated with the OAuthProxy
518func (p *OAuthProxy) GetRedirect(req *http.Request) (redirect string, err error) {
519 err = req.ParseForm()
524 redirect = req.Header.Get("X-Auth-Request-Redirect")
525 if req.Form.Get("rd") != "" {
526 redirect = req.Form.Get("rd")
528 if !p.IsValidRedirect(redirect) {
529 redirect = req.URL.Path
530 if strings.HasPrefix(redirect, p.ProxyPrefix) {
538// splitHostPort separates host and port. If the port is not valid, it returns
539// the entire input as host, and it doesn't check the validity of the host.
540// Unlike net.SplitHostPort, but per RFC 3986, it requires ports to be numeric.
541// *** taken from net/url, modified validOptionalPort() to accept ":*"
542func splitHostPort(hostport string) (host, port string) {
545 colon := strings.LastIndexByte(host, ':')
546 if colon != -1 && validOptionalPort(host[colon:]) {
547 host, port = host[:colon], host[colon+1:]
550 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
551 host = host[1 : len(host)-1]
557// validOptionalPort reports whether port is either an empty string
558// or matches /^:\d*$/
559// *** taken from net/url, modified to accept ":*"
560func validOptionalPort(port string) bool {
561 if port == "" || port == ":*" {
567 for _, b := range port[1:] {
568 if b < '0' || b > '9' {
575// IsValidRedirect checks whether the redirect URL is whitelisted
576func (p *OAuthProxy) IsValidRedirect(redirect string) bool {
578 case strings.HasPrefix(redirect, "/") && !strings.HasPrefix(redirect, "//") && !invalidRedirectRegex.MatchString(redirect):
580 case strings.HasPrefix(redirect, "http://") || strings.HasPrefix(redirect, "https://"):
581 redirectURL, err := url.Parse(redirect)
585 redirectHostname := redirectURL.Hostname()
587 for _, domain := range p.whitelistDomains {
588 domainHostname, domainPort := splitHostPort(strings.TrimLeft(domain, "."))
589 if domainHostname == "" {
593 if (redirectHostname == domainHostname) || (strings.HasPrefix(domain, ".") && strings.HasSuffix(redirectHostname, domainHostname)) {
594 // the domain names match, now validate the ports
595 // if the whitelisted domain's port is '*', allow all ports
596 // if the whitelisted domain contains a specific port, only allow that port
597 // if the whitelisted domain doesn't contain a port at all, only allow empty redirect ports ie http and https
598 redirectPort := redirectURL.Port()
599 if (domainPort == "*") ||
600 (domainPort == redirectPort) ||
601 (domainPort == "" && redirectPort == "") {
613// IsWhitelistedRequest is used to check if auth should be skipped for this request
614func (p *OAuthProxy) IsWhitelistedRequest(req *http.Request) bool {
615 isPreflightRequestAllowed := p.skipAuthPreflight && req.Method == "OPTIONS"
616 return isPreflightRequestAllowed || p.IsWhitelistedPath(req.URL.Path)
619// IsWhitelistedPath is used to check if the request path is allowed without auth
620func (p *OAuthProxy) IsWhitelistedPath(path string) bool {
621 for _, u := range p.compiledRegex {
622 if u.MatchString(path) {
629func getRemoteAddr(req *http.Request) (s string) {
631 if req.Header.Get("X-Real-IP") != "" {
632 s += fmt.Sprintf(" (%q)", req.Header.Get("X-Real-IP"))
637func (p *OAuthProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
638 switch path := req.URL.Path; {
639 case path == p.RobotsPath:
641 case path == p.PingPath:
643 case p.IsWhitelistedRequest(req):
644 p.serveMux.ServeHTTP(rw, req)
645 case path == p.SignInPath:
647 case path == p.SignOutPath:
649 case path == p.OAuthStartPath:
650 p.OAuthStart(rw, req)
651 case path == p.OAuthCallbackPath:
652 p.OAuthCallback(rw, req)
653 case path == p.AuthOnlyPath:
654 p.AuthenticateOnly(rw, req)
655 case path == p.UserInfoPath:
662// SignIn serves a page prompting users to sign in
663func (p *OAuthProxy) SignIn(rw http.ResponseWriter, req *http.Request) {
664 redirect, err := p.GetRedirect(req)
666 logger.Printf("Error obtaining redirect: %s", err.Error())
667 p.ErrorPage(rw, 500, "Internal Error", err.Error())
671 user, ok := p.ManualSignIn(rw, req)
673 session := &sessionsapi.SessionState{User: user}
674 p.SaveSession(rw, req, session)
675 http.Redirect(rw, req, redirect, 302)
677 if p.SkipProviderButton {
678 p.OAuthStart(rw, req)
680 p.SignInPage(rw, req, http.StatusOK)
685//UserInfo endpoint outputs session email and preferred username in JSON format
686func (p *OAuthProxy) UserInfo(rw http.ResponseWriter, req *http.Request) {
688 session, err := p.getAuthenticatedSession(rw, req)
690 http.Error(rw, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
694 Email string `json:"email"`
695 PreferredUsername string `json:"preferredUsername,omitempty"`
697 Email: session.Email,
698 PreferredUsername: session.PreferredUsername,
700 rw.Header().Set("Content-Type", "application/json")
701 rw.WriteHeader(http.StatusOK)
702 json.NewEncoder(rw).Encode(userInfo)
705// SignOut sends a response to clear the authentication cookie
706func (p *OAuthProxy) SignOut(rw http.ResponseWriter, req *http.Request) {
707 redirect, err := p.GetRedirect(req)
709 logger.Printf("Error obtaining redirect: %s", err.Error())
710 p.ErrorPage(rw, 500, "Internal Error", err.Error())
713 p.ClearSessionCookie(rw, req)
714 http.Redirect(rw, req, redirect, 302)
717// OAuthStart starts the OAuth2 authentication flow
718func (p *OAuthProxy) OAuthStart(rw http.ResponseWriter, req *http.Request) {
719 nonce, err := encryption.Nonce()
721 logger.Printf("Error obtaining nonce: %s", err.Error())
722 p.ErrorPage(rw, 500, "Internal Error", err.Error())
725 p.SetCSRFCookie(rw, req, nonce)
726 redirect, err := p.GetRedirect(req)
728 logger.Printf("Error obtaining redirect: %s", err.Error())
729 p.ErrorPage(rw, 500, "Internal Error", err.Error())
732 redirectURI := p.GetRedirectURI(req.Host)
733 http.Redirect(rw, req, p.provider.GetLoginURL(redirectURI, fmt.Sprintf("%v:%v", nonce, redirect)), 302)
736// OAuthCallback is the OAuth2 authentication flow callback that finishes the
737// OAuth2 authentication flow
738func (p *OAuthProxy) OAuthCallback(rw http.ResponseWriter, req *http.Request) {
739 remoteAddr := getRemoteAddr(req)
741 // finish the oauth cycle
742 err := req.ParseForm()
744 logger.Printf("Error while parsing OAuth2 callback: %s" + err.Error())
745 p.ErrorPage(rw, 500, "Internal Error", err.Error())
748 errorString := req.Form.Get("error")
749 if errorString != "" {
750 logger.Printf("Error while parsing OAuth2 callback: %s ", errorString)
751 p.ErrorPage(rw, 403, "Permission Denied", errorString)
755 session, err := p.redeemCode(req.Host, req.Form.Get("code"))
757 logger.Printf("Error redeeming code during OAuth2 callback: %s ", err.Error())
758 p.ErrorPage(rw, 500, "Internal Error", "Internal Error")
762 s := strings.SplitN(req.Form.Get("state"), ":", 2)
764 logger.Printf("Error while parsing OAuth2 state: invalid length")
765 p.ErrorPage(rw, 500, "Internal Error", "Invalid State")
770 c, err := req.Cookie(p.CSRFCookieName)
772 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unable too obtain CSRF cookie")
773 p.ErrorPage(rw, 403, "Permission Denied", err.Error())
776 p.ClearCSRFCookie(rw, req)
777 if c.Value != nonce {
778 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: csrf token mismatch, potential attack")
779 p.ErrorPage(rw, 403, "Permission Denied", "csrf failed")
783 if !p.IsValidRedirect(redirect) {
787 // set cookie, or deny
788 if p.Validator(session.Email) && p.provider.ValidateGroup(session.Email) {
789 logger.PrintAuthf(session.Email, req, logger.AuthSuccess, "Authenticated via OAuth2: %s", session)
790 err := p.SaveSession(rw, req, session)
792 logger.Printf("%s %s", remoteAddr, err)
793 p.ErrorPage(rw, 500, "Internal Error", "Internal Error")
796 http.Redirect(rw, req, redirect, 302)
798 logger.PrintAuthf(session.Email, req, logger.AuthFailure, "Invalid authentication via OAuth2: unauthorized")
799 p.ErrorPage(rw, 403, "Permission Denied", "Invalid Account")
803// AuthenticateOnly checks whether the user is currently logged in
804func (p *OAuthProxy) AuthenticateOnly(rw http.ResponseWriter, req *http.Request) {
805 session, err := p.getAuthenticatedSession(rw, req)
807 http.Error(rw, "unauthorized request", http.StatusUnauthorized)
811 // we are authenticated
812 p.addHeadersForProxying(rw, req, session)
813 rw.WriteHeader(http.StatusAccepted)
816// Proxy proxies the user request if the user is authenticated else it prompts
817// them to authenticate
818func (p *OAuthProxy) Proxy(rw http.ResponseWriter, req *http.Request) {
819 session, err := p.getAuthenticatedSession(rw, req)
822 // we are authenticated
823 p.addHeadersForProxying(rw, req, session)
824 p.serveMux.ServeHTTP(rw, req)
827 // we need to send the user to a login screen
829 // no point redirecting an AJAX request
830 p.ErrorJSON(rw, http.StatusUnauthorized)
834 if p.SkipProviderButton {
835 p.OAuthStart(rw, req)
837 p.SignInPage(rw, req, http.StatusForbidden)
842 logger.Printf("Unexpected internal error: %s", err)
843 p.ErrorPage(rw, http.StatusInternalServerError,
844 "Internal Error", "Internal Error")
849// getAuthenticatedSession checks whether a user is authenticated and returns a session object and nil error if so
850// Returns nil, ErrNeedsLogin if user needs to login.
851// Set-Cookie headers may be set on the response as a side-effect of calling this method.
852func (p *OAuthProxy) getAuthenticatedSession(rw http.ResponseWriter, req *http.Request) (*sessionsapi.SessionState, error) {
853 var session *sessionsapi.SessionState
855 var saveSession, clearSession, revalidated bool
857 if p.skipJwtBearerTokens && req.Header.Get("Authorization") != "" {
858 session, err = p.GetJwtSession(req)
860 logger.Printf("Error retrieving session from token in Authorization header: %s", err)
867 remoteAddr := getRemoteAddr(req)
869 session, err = p.LoadCookiedSession(req)
871 logger.Printf("Error loading cookied session: %s", err)
875 if session.Age() > p.CookieRefresh && p.CookieRefresh != time.Duration(0) {
876 logger.Printf("Refreshing %s old session cookie for %s (refresh after %s)", session.Age(), session, p.CookieRefresh)
880 if ok, err := p.provider.RefreshSessionIfNeeded(session); err != nil {
881 logger.Printf("%s removing session. error refreshing access token %s %s", remoteAddr, err, session)
891 if session != nil && session.IsExpired() {
892 logger.Printf("Removing session: token expired %s", session)
898 if saveSession && !revalidated && session != nil && session.AccessToken != "" {
899 if !p.provider.ValidateSessionState(session) {
900 logger.Printf("Removing session: error validating %s", session)
907 if session != nil && session.Email != "" && !p.Validator(session.Email) {
908 logger.Printf(session.Email, req, logger.AuthFailure, "Invalid authentication via session: removing session %s", session)
914 if saveSession && session != nil {
915 err = p.SaveSession(rw, req, session)
917 logger.PrintAuthf(session.Email, req, logger.AuthError, "Save session error %s", err)
923 p.ClearSessionCookie(rw, req)
927 session, err = p.CheckBasicAuth(req)
929 logger.Printf("Error during basic auth validation: %s", err)
934 return nil, ErrNeedsLogin
940// addHeadersForProxying adds the appropriate headers the request / response for proxying
941func (p *OAuthProxy) addHeadersForProxying(rw http.ResponseWriter, req *http.Request, session *sessionsapi.SessionState) {
943 if p.PreferEmailToUser && session.Email != "" {
944 req.SetBasicAuth(session.Email, p.BasicAuthPassword)
945 req.Header["X-Forwarded-User"] = []string{session.Email}
946 req.Header.Del("X-Forwarded-Email")
948 req.SetBasicAuth(session.User, p.BasicAuthPassword)
949 req.Header["X-Forwarded-User"] = []string{session.User}
950 if session.Email != "" {
951 req.Header["X-Forwarded-Email"] = []string{session.Email}
953 req.Header.Del("X-Forwarded-Email")
956 if session.PreferredUsername != "" {
957 req.Header["X-Forwarded-Preferred-Username"] = []string{session.PreferredUsername}
959 req.Header.Del("X-Forwarded-Preferred-Username")
963 if p.PassUserHeaders {
964 if p.PreferEmailToUser && session.Email != "" {
965 req.Header["X-Forwarded-User"] = []string{session.Email}
966 req.Header.Del("X-Forwarded-Email")
968 req.Header["X-Forwarded-User"] = []string{session.User}
969 if session.Email != "" {
970 req.Header["X-Forwarded-Email"] = []string{session.Email}
972 req.Header.Del("X-Forwarded-Email")
976 if session.PreferredUsername != "" {
977 req.Header["X-Forwarded-Preferred-Username"] = []string{session.PreferredUsername}
979 req.Header.Del("X-Forwarded-Preferred-Username")
983 if p.SetXAuthRequest {
984 rw.Header().Set("X-Auth-Request-User", session.User)
985 if session.Email != "" {
986 rw.Header().Set("X-Auth-Request-Email", session.Email)
988 rw.Header().Del("X-Auth-Request-Email")
990 if session.PreferredUsername != "" {
991 rw.Header().Set("X-Auth-Request-Preferred-Username", session.PreferredUsername)
993 rw.Header().Del("X-Auth-Request-Preferred-Username")
996 if p.PassAccessToken {
997 if session.AccessToken != "" {
998 rw.Header().Set("X-Auth-Request-Access-Token", session.AccessToken)
1000 rw.Header().Del("X-Auth-Request-Access-Token")
1005 if p.PassAccessToken {
1006 if session.AccessToken != "" {
1007 req.Header["X-Forwarded-Access-Token"] = []string{session.AccessToken}
1009 req.Header.Del("X-Forwarded-Access-Token")
1013 if p.PassAuthorization {
1014 if session.IDToken != "" {
1015 req.Header["Authorization"] = []string{fmt.Sprintf("Bearer %s", session.IDToken)}
1017 req.Header.Del("Authorization")
1020 if p.SetAuthorization {
1021 if session.IDToken != "" {
1022 rw.Header().Set("Authorization", fmt.Sprintf("Bearer %s", session.IDToken))
1024 rw.Header().Del("Authorization")
1028 if session.Email == "" {
1029 rw.Header().Set("GAP-Auth", session.User)
1031 rw.Header().Set("GAP-Auth", session.Email)
1035// CheckBasicAuth checks the requests Authorization header for basic auth
1036// credentials and authenticates these against the proxies HtpasswdFile
1037func (p *OAuthProxy) CheckBasicAuth(req *http.Request) (*sessionsapi.SessionState, error) {
1038 if p.HtpasswdFile == nil {
1041 auth := req.Header.Get("Authorization")
1045 s := strings.SplitN(auth, " ", 2)
1046 if len(s) != 2 || s[0] != "Basic" {
1047 return nil, fmt.Errorf("invalid Authorization header %s", req.Header.Get("Authorization"))
1049 b, err := b64.StdEncoding.DecodeString(s[1])
1053 pair := strings.SplitN(string(b), ":", 2)
1055 return nil, fmt.Errorf("invalid format %s", b)
1057 if p.HtpasswdFile.Validate(pair[0], pair[1]) {
1058 logger.PrintAuthf(pair[0], req, logger.AuthSuccess, "Authenticated via basic auth and HTpasswd File")
1059 return &sessionsapi.SessionState{User: pair[0]}, nil
1061 logger.PrintAuthf(pair[0], req, logger.AuthFailure, "Invalid authentication via basic auth: not in Htpasswd File")
1065// isAjax checks if a request is an ajax request
1066func isAjax(req *http.Request) bool {
1067 acceptValues, ok := req.Header["accept"]
1069 acceptValues = req.Header["Accept"]
1071 const ajaxReq = applicationJSON
1072 for _, v := range acceptValues {
1080// ErrorJSON returns the error code with an application/json mime type
1081func (p *OAuthProxy) ErrorJSON(rw http.ResponseWriter, code int) {
1082 rw.Header().Set("Content-Type", applicationJSON)
1083 rw.WriteHeader(code)
1086// GetJwtSession loads a session based on a JWT token in the authorization header.
1087func (p *OAuthProxy) GetJwtSession(req *http.Request) (*sessionsapi.SessionState, error) {
1088 rawBearerToken, err := p.findBearerToken(req)
1093 ctx := context.Background()
1094 var session *sessionsapi.SessionState
1095 for _, verifier := range p.jwtBearerVerifiers {
1096 bearerToken, err := verifier.Verify(ctx, rawBearerToken)
1099 logger.Printf("failed to verify bearer token: %v", err)
1104 Subject string `json:"sub"`
1105 Email string `json:"email"`
1106 Verified *bool `json:"email_verified"`
1107 PreferredUsername string `json:"preferred_username"`
1110 if err := bearerToken.Claims(&claims); err != nil {
1111 return nil, fmt.Errorf("failed to parse bearer token claims: %v", err)
1114 if claims.Email == "" {
1115 claims.Email = claims.Subject
1118 if claims.Verified != nil && !*claims.Verified {
1119 return nil, fmt.Errorf("email in id_token (%s) isn't verified", claims.Email)
1122 session = &sessionsapi.SessionState{
1123 AccessToken: rawBearerToken,
1124 IDToken: rawBearerToken,
1126 ExpiresOn: bearerToken.Expiry,
1127 Email: claims.Email,
1129 PreferredUsername: claims.PreferredUsername,
1133 return nil, fmt.Errorf("unable to verify jwt token %s", req.Header.Get("Authorization"))
1136// findBearerToken finds a valid JWT token from the Authorization header of a given request.
1137func (p *OAuthProxy) findBearerToken(req *http.Request) (string, error) {
1138 auth := req.Header.Get("Authorization")
1139 s := strings.SplitN(auth, " ", 2)
1141 return "", fmt.Errorf("invalid authorization header %s", auth)
1143 jwtRegex := regexp.MustCompile(`^eyJ[a-zA-Z0-9_-]*\.eyJ[a-zA-Z0-9_-]*\.[a-zA-Z0-9_-]+$`)
1144 var rawBearerToken string
1145 if s[0] == "Bearer" && jwtRegex.MatchString(s[1]) {
1146 rawBearerToken = s[1]
1147 } else if s[0] == "Basic" {
1148 // Check if we have a Bearer token masquerading in Basic
1149 b, err := b64.StdEncoding.DecodeString(s[1])
1153 pair := strings.SplitN(string(b), ":", 2)
1155 return "", fmt.Errorf("invalid format %s", b)
1157 user, password := pair[0], pair[1]
1159 // check user, user+password, or just password for a token
1160 if jwtRegex.MatchString(user) {
1161 // Support blank passwords or magic `x-oauth-basic` passwords - nothing else
1162 if password == "" || password == "x-oauth-basic" {
1163 rawBearerToken = user
1165 } else if jwtRegex.MatchString(password) {
1166 // support passwords and ignore user
1167 rawBearerToken = password
1170 if rawBearerToken == "" {
1171 return "", fmt.Errorf("no valid bearer token found in authorization header")
1174 return rawBearerToken, nil
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