當前位置: 首頁>>代碼示例>>Golang>>正文


Golang go-http-auth.NewBasicAuthenticator函數代碼示例

本文整理匯總了Golang中github.com/abbot/go-http-auth.NewBasicAuthenticator函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewBasicAuthenticator函數的具體用法?Golang NewBasicAuthenticator怎麽用?Golang NewBasicAuthenticator使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewBasicAuthenticator函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: CreateFilter

// Creates out basicAuth Filter
// The first params specifies the used htpasswd file
// The second is optional and defines the realm name
func (spec *basicSpec) CreateFilter(config []interface{}) (filters.Filter, error) {
	if len(config) == 0 {
		return nil, filters.ErrInvalidFilterParameters
	}

	configFile, ok := config[0].(string)
	if !ok {
		return nil, filters.ErrInvalidFilterParameters
	}

	realmName := DefaultRealmName

	if len(config) == 2 {
		if definedName, ok := config[1].(string); ok {
			realmName = definedName
		}
	}

	htpasswd := auth.HtpasswdFileProvider(configFile)
	authenticator := auth.NewBasicAuthenticator(realmName, htpasswd)

	return &basic{
		authenticator:   authenticator,
		realmDefinition: ForceBasicAuthHeaderValue + `"` + realmName + `"`,
	}, nil
}
開發者ID:zalando,項目名稱:skipper,代碼行數:29,代碼來源:basic.go

示例2: main

// main sets up the routes (thanks Gorilla!).
func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", showIndex)
	r.HandleFunc("/about", showAbout)
	r.HandleFunc("/archives", showArchives)
	r.PathPrefix("/static").
		Handler(http.StripPrefix("/static",
			http.FileServer(http.Dir(staticPath))))

	// Password protect data refreshing
	authenticator := auth.NewBasicAuthenticator(
		"Refresh data", auth.HtpasswdFileProvider(*htpasswd))
	r.HandleFunc("/refresh", auth.JustCheck(authenticator, showRefresh))

	// These must be last. The first shows blog posts, the second adds comments.
	r.HandleFunc("/{postname}", showPost).Methods("GET")
	r.HandleFunc("/{postname}", addComment).Methods("POST")

	// Captcha!
	http.Handle("/captcha/",
		captcha.Server(captcha.StdWidth, captcha.StdHeight))

	// Okay, let Gorilla do its work.
	http.Handle("/", r)
	http.ListenAndServe(":8082", nil)
}
開發者ID:jacobxk,項目名稱:burntsushi-blog,代碼行數:27,代碼來源:blog.go

示例3: RegisterHandlers

func RegisterHandlers(mux httpMux.Mux, containerManager manager.Manager, httpAuthFile, httpAuthRealm, httpDigestFile, httpDigestRealm, prometheusEndpoint string) error {
	// Basic health handler.
	if err := healthz.RegisterHandler(mux); err != nil {
		return fmt.Errorf("failed to register healthz handler: %s", err)
	}

	// Validation/Debug handler.
	mux.HandleFunc(validate.ValidatePage, func(w http.ResponseWriter, r *http.Request) {
		err := validate.HandleRequest(w, containerManager)
		if err != nil {
			fmt.Fprintf(w, "%s", err)
		}
	})

	// Register API handler.
	if err := api.RegisterHandlers(mux, containerManager); err != nil {
		return fmt.Errorf("failed to register API handlers: %s", err)
	}

	// Redirect / to containers page.
	mux.Handle("/", http.RedirectHandler(pages.ContainersPage, http.StatusTemporaryRedirect))

	var authenticated bool = false

	// Setup the authenticator object
	if httpAuthFile != "" {
		glog.Infof("Using auth file %s", httpAuthFile)
		secrets := auth.HtpasswdFileProvider(httpAuthFile)
		authenticator := auth.NewBasicAuthenticator(httpAuthRealm, secrets)
		mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
		if err := pages.RegisterHandlersBasic(mux, containerManager, authenticator); err != nil {
			return fmt.Errorf("failed to register pages auth handlers: %s", err)
		}
		authenticated = true
	}
	if httpAuthFile == "" && httpDigestFile != "" {
		glog.Infof("Using digest file %s", httpDigestFile)
		secrets := auth.HtdigestFileProvider(httpDigestFile)
		authenticator := auth.NewDigestAuthenticator(httpDigestRealm, secrets)
		mux.HandleFunc(static.StaticResource, authenticator.Wrap(staticHandler))
		if err := pages.RegisterHandlersDigest(mux, containerManager, authenticator); err != nil {
			return fmt.Errorf("failed to register pages digest handlers: %s", err)
		}
		authenticated = true
	}

	// Change handler based on authenticator initalization
	if !authenticated {
		mux.HandleFunc(static.StaticResource, staticHandlerNoAuth)
		if err := pages.RegisterHandlersBasic(mux, containerManager, nil); err != nil {
			return fmt.Errorf("failed to register pages handlers: %s", err)
		}
	}

	collector := metrics.NewPrometheusCollector(containerManager)
	prometheus.MustRegister(collector)
	http.Handle(prometheusEndpoint, prometheus.Handler())

	return nil
}
開發者ID:alena1108,項目名稱:kubernetes,代碼行數:60,代碼來源:handlers.go

示例4: main

func main() {
	flag.Parse()

	if *debugPtr == true {
		fmt.Println("Console debug output enabled.")
	}

	urlport := ":" + strconv.Itoa(*portPtr)

	authenticator := auth.NewBasicAuthenticator("sysreport", Secret)

	if *authPtr == true {
		http.HandleFunc("/", authenticator.Wrap(authRootViewHandler))
		http.HandleFunc("/packages", authenticator.Wrap(authPackagesViewHandler))
		http.HandleFunc("/facter", authenticator.Wrap(authFacterViewHandler))
		http.HandleFunc("/ohai", authenticator.Wrap(authOhaiViewHandler))
	} else {
		http.HandleFunc("/", rootViewHandler)
		http.HandleFunc("/packages", packagesViewHandler)
		http.HandleFunc("/facter", facterViewHandler)
		http.HandleFunc("/ohai", ohaiViewHandler)
	}

	if *sslPtr == true {
		http.ListenAndServeTLS(urlport, *cpemPtr, *kpemPtr, nil)
	} else {
		http.ListenAndServe(urlport, nil)
	}
}
開發者ID:spkane,項目名稱:sysreport,代碼行數:29,代碼來源:sysreport.go

示例5: runControlServer

func runControlServer() {
	authenticator := auth.NewBasicAuthenticator("localhost", Secret)
	http.HandleFunc("/server", authenticator.Wrap(ServerActionsHandler))
	http.HandleFunc("/server/status", authenticator.Wrap(ServerStatusHandler))
	http.Handle("/index.html", authenticator.Wrap(indexHandler))
	http.Handle("/", http.FileServer(http.Dir("."+pathSeparator+"html")))
	http.ListenAndServe(config["control-panel"]["address"]+":"+config["control-panel"]["port"], nil)
}
開發者ID:custodian,項目名稱:lifds-cp,代碼行數:8,代碼來源:general.go

示例6: main

func main() {
	log.Printf("Init")
	dbinit()
	defer dbclose()
	authenticator := auth.NewBasicAuthenticator("127.0.0.1", Secret)
	http.HandleFunc("/", authenticator.Wrap(handle))
	log.Printf("Ready")
	http.ListenAndServe(":8080", nil)
}
開發者ID:jlhonora,項目名稱:honorato.org,代碼行數:9,代碼來源:auth.go

示例7: ServeHTTP

func (mp *MainPage) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if mp.BasicAuth {
		staticContentHandler := &Authentication{User: mp.UserName, Password: mp.UserPassword}
		authWrapper := httpauth.NewBasicAuthenticator("Gotail", staticContentHandler.Secret)
		authWrapper.Wrap(mp.AuthTail).ServeHTTP(w, r)
	} else {
		mp.Tail(w, r)
	}
}
開發者ID:skarnecki,項目名稱:gotail,代碼行數:9,代碼來源:main_page.go

示例8: middleware

func middleware(h http.HandlerFunc, middleware ...func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {
	for _, m := range middleware {
		h = m(h)
	}

	// TODO: Get this to only be setup once.
	authenticator := auth.NewBasicAuthenticator(
		"trajectory.com", GetSecret(getLoginConfig()))
	return auth.JustCheck(authenticator, h)
}
開發者ID:nicklenstra-wf,項目名稱:trajectory,代碼行數:10,代碼來源:main.go

示例9: setupWeb

func setupWeb() {
	authenticator := auth.NewBasicAuthenticator(
		"trajectory.com", GetSecret(getLoginConfig()))
	http.HandleFunc(
		"/",
		authenticator.Wrap(func(
			res http.ResponseWriter, req *auth.AuthenticatedRequest) {
			http.FileServer(http.Dir("./web/")).ServeHTTP(res, &req.Request)
		}))
}
開發者ID:nicklenstra-wf,項目名稱:trajectory,代碼行數:10,代碼來源:main.go

示例10: StartHTTPServer

func StartHTTPServer(port string) {

	htpasswd := auth.HtpasswdFileProvider(conf.PasswdFile)
	authenticator := auth.NewBasicAuthenticator("Basic realm", htpasswd)

	http.HandleFunc(ROUTE_INSERT, authenticator.Wrap(insertHandler))
	http.HandleFunc(ROUTE_DELETE, authenticator.Wrap(deleteHandler))
	http.HandleFunc(ROUTE_STATIC, authenticator.Wrap(staticHandler))
	http.HandleFunc(ROUTE_GET, authenticator.Wrap(getHandler))
	http.HandleFunc(ROUTE_LIST, authenticator.Wrap(listHandler))
	//http.ListenAndServe(port, nil)
	http.ListenAndServeTLS(port, conf.TLSPemFile, conf.TLSKeyFile, nil)
}
開發者ID:Pereiro,項目名稱:fstore,代碼行數:13,代碼來源:http.go

示例11: main

func main() {

	flag.Parse()

	// seed the RNG, otherwise we would have same randomness on every startup
	// which should not, but might in worst case interfere with leftover-mails
	// from earlier starts of the binary
	rand.Seed(time.Now().Unix())

	err := parse_conf(*conf_path)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	wg := new(sync.WaitGroup)
	wg.Add(len(globalconf.Servers))

	// now fire up the monitoring jobs
	for _, c := range globalconf.Servers {
		fmt.Println("starting monitoring for config", c["Name"])
		go monitor(c, wg)

		// keep a timedelta between monitoring jobs to avoid strong interference
		time.Sleep(startupOffsetTime)
	}

	fmt.Println("starting HTTP-endpoint")
	if *useAuth {
		authenticator := auth.NewBasicAuthenticator("prometheus", Secret)
		http.HandleFunc(globalconf.Http_endpoint, auth.JustCheck(authenticator, prometheus.Handler().ServeHTTP))
	} else {
		http.Handle(globalconf.Http_endpoint, prometheus.Handler())
	}

	if *useTLS {
		err = http.ListenAndServeTLS(":"+globalconf.Http_port, globalconf.Crt_path, globalconf.Key_path, nil)
	} else {
		err = http.ListenAndServe(":"+globalconf.Http_port, nil)
	}

	if err != nil {
		fmt.Println(err)
	}

	// wait for goroutines to exit
	// otherwise main would terminate and the goroutines monitoring would be killed
	wg.Wait()

}
開發者ID:brian-brazil,項目名稱:mailexporter,代碼行數:51,代碼來源:mailexporter.go

示例12: main

func main() {
	flag.Parse()

	PersistenceObj = GetPersistenceLayer(*persistence)
	if PersistenceObj == nil {
		log.Err("Unable to load persistence plugin " + *persistence)
		panic("Dying")
	}
	var err error
	ConfigObj, err = PersistenceObj.GetConfig()
	if err != nil {
		log.Err("Unable to load config from persistence plugin " + *persistence)
		panic("Dying")
	}

	if ConfigObj.PidFile != *haproxyPidFile {
		ConfigObj.PidFile = *haproxyPidFile
	}

	r := mux.NewRouter()

	// Define paths
	sub := r.PathPrefix("/api").Subrouter()

	// Wire the UI (outside of muxer)
	http.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(*uiLocation))))

	// Display handlers
	sub.HandleFunc("/config", configHandler).Methods("GET")
	sub.HandleFunc("/reload", configReloadHandler).Methods("GET")
	sub.HandleFunc("/backend/{backend}", backendHandler).Methods("GET")
	sub.HandleFunc("/backend/{backend}", backendAddHandler).Methods("POST")
	sub.HandleFunc("/backend/{backend}", backendDeleteHandler).Methods("DELETE")
	sub.HandleFunc("/backend/{backend}/server/{server}", backendServerHandler).Methods("GET")
	sub.HandleFunc("/backend/{backend}/server/{server}", backendServerAddHandler).Methods("POST")
	sub.HandleFunc("/backend/{backend}/server/{server}", backendServerDeleteHandler).Methods("DELETE")

	s := &http.Server{
		Addr:           *bind,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	h := auth.HtpasswdFileProvider(*htpasswd)
	a := auth.NewBasicAuthenticator("haproxy config", h)
	http.Handle("/", a.Wrap(func(w http.ResponseWriter, ar *auth.AuthenticatedRequest) {
		r.ServeHTTP(w, &ar.Request)
	}))
	log.Err(s.ListenAndServe().Error())
}
開發者ID:jbuchbinder,項目名稱:haproxy-config,代碼行數:50,代碼來源:main.go

示例13: main

func main() {
	setLogging()
	config = readConfig(getPath("conf"))

	authenticator := auth.NewBasicAuthenticator(
		"example.com",
		func(user, realm string) string {
			return Secret(config, user, realm)
		})

	http.HandleFunc("/", authenticator.Wrap(handle))
	http.HandleFunc("/last-seen-employees", authenticator.Wrap(showLastSeenEmployees))
	http.ListenAndServe(":8080", nil)

}
開發者ID:d-vandyshev,項目名稱:web_access_acs_orion,代碼行數:15,代碼來源:web_access_acs_orion.go

示例14: Listen

func (h *httpServer) Listen(address string) error {

	fs := http.FileServer(http.Dir("web/assets"))

	secrets := auth.HtpasswdFileProvider(h.secrets)
	authenticator := auth.NewBasicAuthenticator("Basic Realm", secrets)

	http.HandleFunc("/", h.Root)
	http.Handle("/assets/", http.StripPrefix("/assets/", fs))
	http.HandleFunc("/songs", h.Songs)
	http.HandleFunc("/song/", h.Song)
	http.HandleFunc("/ws", ws.Handle)
	http.HandleFunc("/play/", authenticator.Wrap(h.Play))

	return http.ListenAndServe(address, nil)
}
開發者ID:dafiti,項目名稱:buffer,代碼行數:16,代碼來源:httpserver.go

示例15: main

func main() {

	pwd, _ := os.Getwd()

	//Set config path and type
	viper.SetConfigName("config")
	viper.AddConfigPath(pwd)
	viper.AddConfigPath("/etc/ddesktop/")
	viper.SetConfigType("yaml")

	//Read config
	err := viper.ReadInConfig()
	if err != nil {
		log.Fatalln(err)
	}

	log.Println(viper.GetString("container.prefix"))

	//Cleanup existing containers
	dockerhandler.CleanUp()

	//Pull new docker image
	if viper.GetBool("container.pull") {
		dockerhandler.PullImage()
	}

	//Get authentication setting
	htpasswd := auth.HtpasswdFileProvider(viper.GetString("htpasswd.path"))
	authenticator := auth.NewBasicAuthenticator(".ddesktop", htpasswd)

	//Start server
	log.Printf("Starting server on http://0.0.0.0:" + viper.GetString("server.port.http") + " and https://0.0.0.0:" + viper.GetString("server.port.https") + "...")
	http.Handle("/websockify", auth.JustCheck(authenticator, wsproxy.WsProxy()))
	http.HandleFunc("/", auth.JustCheck(authenticator, server.Static()))

	go func() {
		if err := http.ListenAndServeTLS(":"+viper.GetString("server.port.https"), viper.GetString("ssl.cert"), viper.GetString("ssl.key"), nil); err != nil {
			log.Fatalln(err)
		}
	}()
	if err := http.ListenAndServe(":"+viper.GetString("server.port.http"), http.HandlerFunc(server.RedirectHttps)); err != nil {
		log.Fatalln(err)
	}
}
開發者ID:n3r0-ch,項目名稱:ddesktop,代碼行數:44,代碼來源:ddesktop.go


注:本文中的github.com/abbot/go-http-auth.NewBasicAuthenticator函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。