本文整理汇总了Golang中github.com/abbot/go-http-auth.NewBasicAuthenticator函数的典型用法代码示例。如果您正苦于以下问题:Golang NewBasicAuthenticator函数的具体用法?Golang NewBasicAuthenticator怎么用?Golang NewBasicAuthenticator使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewBasicAuthenticator函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: main
func main() {
var mongoUrl = flag.String("db", "petrucho-db", "MongoDB URL")
flag.Parse()
ctx := context.Background()
ctx = db.OpenMongoDB(ctx, "main", *mongoUrl)
defer db.Close(ctx)
kami.Context = ctx
secret := func(email, realm string) string {
u := User{}
users := userStorage(ctx)
err := users.Find(bson.M{"email": email, "confirmed": true}).One(&u)
if err != nil {
return ""
}
return u.Password
}
authenticator := auth.NewBasicAuthenticator("Restricted", secret)
kami.Get("/", homeHandler)
kami.Get("/register", registrationForm)
kami.Post("/register", registerUser)
kami.Get("/confirm/:token", confirmRegistration)
kami.Get("/users", viewAllUsers)
kami.Get("/users/:email", viewUser)
kami.Use("/users/:email/edit", func(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
var username string
authenticator.Wrap(func(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
username = r.Username
})(w, r)
if len(username) == 0 {
return nil
}
return context.WithValue(ctx, "auth", username)
})
kami.Get("/users/:email/edit", editProfileForm)
kami.Post("/users/:email/edit", updateProfile)
kami.Serve()
}
开发者ID:yauhen-l,项目名称:petrucho,代码行数:42,代码来源:petrucho.go
示例17: main
func main() {
folderPath, errpath := osext.ExecutableFolder()
if errpath != nil {
fmt.Printf("Couldn't get cwd. Check permissions!\n")
return
}
if _, err := os.Stat(folderPath + ".htpasswd"); os.IsNotExist(err) {
fmt.Printf(folderPath + ".htpasswd doesn't exist in cwd!\n")
return
}
secrets := auth.HtpasswdFileProvider(folderPath + ".htpasswd")
authenticator := auth.NewBasicAuthenticator("Seyes Echelon", secrets)
http.HandleFunc("/record_log", auth.JustCheck(authenticator, handle))
fmt.Println("Server starting on port " + os.Args[1] + " ....\n")
http.ListenAndServe(":"+os.Args[1], nil)
}
开发者ID:uguratar,项目名称:Echelon,代码行数:21,代码来源:echelon.go
示例18: New
func New(runInDebugMode bool, templatesLocation string, usersPasswordFileLocation string, storageFactory model.VFStorageGroup, srvlog *logs.ServerLog) http.Handler {
if defaultRouter != nil {
return defaultRouter
}
serverlog = srvlog
defaultUserAuthenticator = auth.NewBasicAuthenticator("myrealm", auth.HtpasswdFileProvider(usersPasswordFileLocation))
defaultStorageFactory = storageFactory
results.TemplatesDir = templatesLocation
results.DebugMode = runInDebugMode
defaultRouter = mux.NewRouter()
adminRouter := mux.NewRouter()
apiRouter := mux.NewRouter()
handleVFolder(apiRouter)
handleCtrlPanel(adminRouter)
handlePlayground(apiRouter)
defaultRouter.PathPrefix("/api").Handler(
negroni.New(
negroni.HandlerFunc(authorized),
negroni.Wrap(apiRouter),
),
)
defaultRouter.PathPrefix("/admin").Handler(
negroni.New(
negroni.HandlerFunc(authorized),
negroni.HandlerFunc(adminOnly),
negroni.Wrap(adminRouter),
),
)
defaultRouter.PathPrefix("/static").Handler(http.StripPrefix("/static", http.FileServer(http.Dir("./server/static"))))
return defaultRouter
}
开发者ID:vitormoura,项目名称:Laboratorio,代码行数:39,代码来源:handlers.go
示例19: main
func main() {
programName := os.Args[0]
absPath, _ := filepath.Abs(programName)
haproxyConsoleRoot = path.Dir(path.Dir(absPath))
port := flag.String("p", "9090", "port to run the web server")
configuration := flag.String("config", "", "path to the app config file")
toolMode := flag.Bool("t", false, "run this program as a tool to export data from database to json or from json to database")
flag.Parse()
configPath := *configuration
if configPath == "" {
defaultConfigPath := haproxyConsoleRoot + "/conf/app_conf.ini"
fmt.Printf("You not set the configPath, so try to use the default config path: %s\n", defaultConfigPath)
if _, e := os.Stat(defaultConfigPath); os.IsNotExist(e) {
fmt.Println("Not Exit default config file")
os.Exit(1)
} else {
configPath = defaultConfigPath
}
}
var err error
logger = getLogger()
appConf, err = config.ParseConfig(configPath)
if err != nil {
fmt.Println(err)
return
}
if *toolMode {
// 数据转换存储方式
err := tools.StorageTransform(appConf)
tools.CheckError(err)
} else {
// 存储连接初始化
db, err = applicationDB.InitStoreConnection(appConf)
if err != nil {
logger.Fatalln(err)
os.Exit(1)
}
defer db.Close()
// 请求路由
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(haproxyConsoleRoot+"/static/"))))
// basic auth user: admin, passwd: [email protected]
authenticator := auth.NewBasicAuthenticator("HAProxyConsole", auth.HtpasswdFileProvider(haproxyConsoleRoot+"/conf/md5passwd"))
http.HandleFunc("/applyvport", authenticator.Wrap(applyVPort))
http.HandleFunc("/edittask", authenticator.Wrap(editTask))
http.HandleFunc("/listenlist", authenticator.Wrap(getListenList))
http.HandleFunc("/dellistentask", authenticator.Wrap(delListenTask))
http.HandleFunc("/applyconf", authenticator.Wrap(applyConf))
http.HandleFunc("/statspage", statsPage)
http.HandleFunc("/", authenticator.Wrap(getHomePage))
// 启动http服务
err = http.ListenAndServe(":"+*port, nil)
if err != nil {
logger.Fatalln("ListenAndServe: ", err)
}
}
}
开发者ID:yinwer81,项目名称:haproxyconsole,代码行数:66,代码来源:main.go
示例20: NewHttpBasicAuthenticator
func NewHttpBasicAuthenticator(htpasswdFile string) *HttpBasicAuthenticator {
return &HttpBasicAuthenticator{
//secretFunc: httpauth.HtpasswdFileProvider(htpasswdFile),
basicAuth: httpauth.NewBasicAuthenticator("vindalu", httpauth.HtpasswdFileProvider(htpasswdFile)),
}
}
开发者ID:vindalu,项目名称:vindalu,代码行数:6,代码来源:basic_auth.go
注:本文中的github.com/abbot/go-http-auth.NewBasicAuthenticator函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论