switchable auth scheme based on service config (#12)

This commit is contained in:
Michael Quigley 2022-08-16 11:41:04 -04:00
parent b510190910
commit 83b573bfa8
No known key found for this signature in database
GPG Key ID: 9B60314A9DD20A62

View File

@ -44,7 +44,7 @@ func Run(cfg *Config) error {
{Username: "hello", Password: "world"}, {Username: "hello", Password: "world"},
}, },
} }
return http.ListenAndServe(cfg.Address, basicAuth(util.NewProxyHandler(proxy), users, "zrok")) return http.ListenAndServe(cfg.Address, basicAuth(util.NewProxyHandler(proxy), users, "zrok", &resolver{}, zCtx))
} }
type resolver struct{} type resolver struct{}
@ -165,14 +165,23 @@ func getRefreshedService(name string, ctx ziti.Context) (*edge.Service, bool) {
return svc, found return svc, found
} }
func basicAuth(handler http.Handler, users *model.BasicAuth, realm string) http.HandlerFunc { func basicAuth(handler http.Handler, users *model.BasicAuth, realm string, rslv ProxyServiceResolver, ctx ziti.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
svcName := rslv.Service(r.Host)
if svc, found := getRefreshedService(svcName, ctx); found {
if cfg, found := svc.Configs[model.ZrokProxyConfig]; found {
if scheme, found := cfg["auth_scheme"]; found {
switch scheme {
case model.None:
handler.ServeHTTP(w, r)
return
case model.Basic:
inUser, inPass, ok := r.BasicAuth() inUser, inPass, ok := r.BasicAuth()
if !ok { if !ok {
writeUnauthorizedResponse(w, realm) writeUnauthorizedResponse(w, realm)
return return
} }
authed := false authed := false
for _, v := range users.Users { for _, v := range users.Users {
if subtle.ConstantTimeCompare([]byte(inUser), []byte(v.Username)) == 1 && subtle.ConstantTimeCompare([]byte(inPass), []byte(v.Password)) == 1 { if subtle.ConstantTimeCompare([]byte(inUser), []byte(v.Username)) == 1 && subtle.ConstantTimeCompare([]byte(inPass), []byte(v.Password)) == 1 {
@ -180,15 +189,17 @@ func basicAuth(handler http.Handler, users *model.BasicAuth, realm string) http.
break break
} }
} }
if !authed { if !authed {
writeUnauthorizedResponse(w, realm) writeUnauthorizedResponse(w, realm)
return return
} }
handler.ServeHTTP(w, r) handler.ServeHTTP(w, r)
} }
} }
}
}
}
}
func writeUnauthorizedResponse(w http.ResponseWriter, realm string) { func writeUnauthorizedResponse(w http.ResponseWriter, realm string) {
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`) w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)