当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.BasicAuth方法代码示例

本文整理汇总了Golang中net/http.Request.BasicAuth方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.BasicAuth方法的具体用法?Golang Request.BasicAuth怎么用?Golang Request.BasicAuth使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.BasicAuth方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: AuthenticateRequest

// AuthenticateRequest authenticates the request using the "Authorization: Basic" header in the request
func (a *Authenticator) AuthenticateRequest(req *http.Request) (user.Info, bool, error) {
	username, password, found := req.BasicAuth()
	if !found {
		return nil, false, nil
	}
	return a.auth.AuthenticatePassword(username, password)
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:8,代码来源:basicauth.go

示例2: parse

func (op *obtainTokenOp) parse(jp jsonParser, r *http.Request) error {
	v := mux.Vars(r)
	op.serverLocation = strings.ToLower(v["serverLocation"])

	// extract appID and appKey as BASIC auth.
	u, p, ok := r.BasicAuth()
	if !ok {
		return ErrNoAuthorization
	}
	if u == "" || p == "" {
		return ErrInvalidGrant
	}
	op.appID, op.appKey = u, p

	m, err := jp.parseJSON(r)
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	x := dproxy.New(m)
	op.username, err = x.M("username").String()
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	op.password, err = x.M("password").String()
	if err != nil {
		return newInvalidUsernamePassword(err)
	}
	return nil
}
开发者ID:KiiPlatform,项目名称:gateway-agent,代码行数:29,代码来源:operation.go

示例3: ParseRequest

func (as *AuthServer) ParseRequest(req *http.Request) (*AuthRequest, error) {
	ar := &AuthRequest{RemoteAddr: req.RemoteAddr, Actions: []string{}}
	user, password, haveBasicAuth := req.BasicAuth()
	if haveBasicAuth {
		ar.User = user
		ar.Password = authn.PasswordString(password)
	}
	ar.Account = req.FormValue("account")
	if ar.Account == "" {
		ar.Account = ar.User
	} else if haveBasicAuth && ar.Account != ar.User {
		return nil, fmt.Errorf("user and account are not the same (%q vs %q)", ar.User, ar.Account)
	}
	ar.Service = req.FormValue("service")
	scope := req.FormValue("scope")
	if scope != "" {
		parts := strings.Split(scope, ":")
		if len(parts) != 3 {
			return nil, fmt.Errorf("invalid scope: %q", scope)
		}
		ar.Type = parts[0]
		ar.Name = parts[1]
		ar.Actions = strings.Split(parts[2], ",")
		sort.Strings(ar.Actions)
	}
	return ar, nil
}
开发者ID:rhlmhrtr,项目名称:docker_auth,代码行数:27,代码来源:server.go

示例4: ServeHTTP

func (b *basicauth) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	// don't request passwords for the websocket interface (for now)
	// because 'wscat' doesn't support that.
	if r.RequestURI == "/monitor" {
		b.h.ServeHTTP(w, r)
		return
	}

	cfgMutex.RLock()
	user := Config.HTTP.User
	password := Config.HTTP.Password
	cfgMutex.RUnlock()

	if len(user) == 0 {
		b.h.ServeHTTP(w, r)
		return
	}

	ruser, rpass, ok := r.BasicAuth()
	if ok {
		if ruser == user && rpass == password {
			b.h.ServeHTTP(w, r)
			return
		}
	}

	w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, "GeoDNS Status"))
	http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
	return
}
开发者ID:cpronier,项目名称:geodns,代码行数:31,代码来源:monitor.go

示例5: parseCredentials

// parseCredentials parses a request and returns the authentication credentials.
// The credentials may be present as URL query params, or as a Basic
// Authentication header.
// As params: http://127.0.0.1/query?u=username&p=password
// As basic auth: http://username:[email protected]
// As Bearer token in Authorization header: Bearer <JWT_TOKEN_BLOB>
func parseCredentials(r *http.Request) (*credentials, error) {
	q := r.URL.Query()

	// Check for the HTTP Authorization header.
	if s := r.Header.Get("Authorization"); s != "" {
		// Check for Bearer token.
		strs := strings.Split(s, " ")
		if len(strs) == 2 && strs[0] == "Bearer" {
			return &credentials{
				Method: BearerAuthentication,
				Token:  strs[1],
			}, nil
		}

		// Check for basic auth.
		if u, p, ok := r.BasicAuth(); ok {
			return &credentials{
				Method:   UserAuthentication,
				Username: u,
				Password: p,
			}, nil
		}
	}

	// Check for username and password in URL params.
	if u, p := q.Get("u"), q.Get("p"); u != "" && p != "" {
		return &credentials{
			Method:   UserAuthentication,
			Username: u,
			Password: p,
		}, nil
	}

	return nil, fmt.Errorf("unable to parse authentication credentials")
}
开发者ID:CrazyUncleJack,项目名称:influxdb,代码行数:41,代码来源:handler.go

示例6: RequestHandler

func (hli *HttpListenInput) RequestHandler(w http.ResponseWriter, req *http.Request) {
	var err error

	if hli.conf.AuthType == "Basic" {
		if hli.conf.Username != "" && hli.conf.Password != "" {
			user, pass, ok := req.BasicAuth()
			if !ok || user != hli.conf.Username || pass != hli.conf.Password {
				err = fmt.Errorf("Basic Auth Failed")
				hli.ir.LogError(err)
			}
		}
	}
	if hli.conf.AuthType == "API" {
		if hli.conf.Key != "" {
			api_key := req.Header.Get("X-API-Key")
			if api_key != hli.conf.Key {
				err = fmt.Errorf("API Auth Failed")
				hli.ir.LogError(err)
			}
		}
	}
	if err == nil {
		sRunner := hli.ir.NewSplitterRunner(req.RemoteAddr)
		if !sRunner.UseMsgBytes() {
			sRunner.SetPackDecorator(hli.makePackDecorator(req))
		}
		err = sRunner.SplitStreamNullSplitterToEOF(req.Body, nil)
		if err != nil && err != io.EOF {
			hli.ir.LogError(fmt.Errorf("receiving request body: %s", err.Error()))
		}
		req.Body.Close()
		sRunner.Done()
	}
}
开发者ID:Nitro,项目名称:heka,代码行数:34,代码来源:http_listen_input.go

示例7: reportError

// HTTP handler to decode request body and hand off to
// vendor-specific reporters
// This is where we could fan out to multiple reporters
// or detect reporters based on ENV vars
func reportError(w http.ResponseWriter, r *http.Request) {
	// basic auth
	_, password, ok := r.BasicAuth()
	passwordOk := (password == os.Getenv("PASSWORD1") || password == os.Getenv("PASSWORD2"))
	if !(ok && passwordOk) {
		w.Header().Set("WWW-Authenticate", `Basic realm="Errors"`)
		w.WriteHeader(401)
		w.Write([]byte("unauthorized"))
		return
	}

	// decode request body into ErrorPost
	var errorPost ErrorPost
	decoder := json.NewDecoder(r.Body)
	err := decoder.Decode(&errorPost)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// report errors
	reportToRollbar(errorPost)

	// all ok
	w.Write([]byte("ok"))
}
开发者ID:convox-archive,项目名称:error-catcher,代码行数:30,代码来源:web.go

示例8: FromRequest

// FromRequest inspects the HTTP Authorization header of the given request
// and tries to identify a passenger.
func FromRequest(ctx context.Context, r *http.Request) (*Passenger, error) {
	cookie, err := r.Cookie("token")
	if err != nil && err != http.ErrNoCookie {
		return nil, err
	}
	if err == nil {
		return FromToken(ctx, cookie.Value)
	}

	auth := ""
	if auth = r.Header.Get("Authorization"); auth == "" {
		return nil, ErrNoAuthHeader
	}

	if strings.HasPrefix(auth, "Token ") {
		return FromToken(ctx, auth[6:])
	}

	username, password, ok := "", "", false
	if username, password, ok = r.BasicAuth(); !ok {
		return nil, ErrUnkAuthHeader
	}

	return FromBasicAuth(ctx, username, password)
}
开发者ID:flowlo,项目名称:coduno-api,代码行数:27,代码来源:passenger.go

示例9: authenticator

// authenticator reads the username from the HTTP basic authentication header
// and validates the token. It sets the "user" key in the context to the
// user associated with the token.
func authenticator(c siesta.Context, w http.ResponseWriter, r *http.Request,
	quit func()) {
	// Context variables
	requestID := c.Get("request-id").(string)
	db := c.Get("db").(*DB)

	// Check for a token in the HTTP basic authentication username field.
	token, _, ok := r.BasicAuth()
	if ok {
		user, err := db.validateToken(token)
		if err != nil {
			log.Printf("[Req %s] Did not provide a valid token", requestID)
			c.Set("status-code", http.StatusUnauthorized)
			c.Set("error", "invalid token")
			quit()
			return
		}

		log.Printf("[Req %s] Provided a token for: %s", requestID, user)

		// Add the user to the context.
		c.Set("user", user)
	} else {
		log.Printf("[Req %s] Did not provide a token", requestID)

		c.Set("error", "token required")
		c.Set("status-code", http.StatusUnauthorized)

		// Exit the chain here.
		quit()
		return
	}
}
开发者ID:se77en,项目名称:siesta,代码行数:36,代码来源:middleware.go

示例10: IssueToken

// IssueToken handles all requests going to tokens endpoint.
func IssueToken(w http.ResponseWriter, req *http.Request, cfg config) {
	provider := cfg.provider
	username, password, ok := req.BasicAuth()
	cinfo, err := provider.AuthenticateClient(username, password)
	if !ok || err != nil {
		render.JSON(w, render.Options{
			Status: http.StatusBadRequest,
			Data:   ErrUnauthorizedClient,
		})
		return
	}

	grantType := req.FormValue("grant_type")
	switch grantType {
	case "authorization_code":
		authCodeGrant2(w, req, cfg, cinfo)
	case "client_credentials":
		clientCredentialsGrant(w, req, cfg, cinfo)
	case "password":
		resourceOwnerCredentialsGrant(w, req, cfg, cinfo)
	case "refresh_token":
		refreshToken(w, req, cfg, cinfo)
	default:
		render.JSON(w, render.Options{
			Status: http.StatusBadRequest,
			Data:   ErrUnsupportedGrantType,
		})
		return
	}
}
开发者ID:thanzen,项目名称:oauth2,代码行数:31,代码来源:tokens.go

示例11: collect

func collect(w http.ResponseWriter, r *http.Request) {
	username, password, ok := r.BasicAuth()
	if ok {
		_ = fmt.Sprintf("Username: %s | Password: %s", username, password)
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Fatal(err)
		}
		mxj.XmlCharsetReader = charset.NewReader
		m, err := mxj.NewMapXml(body) // unmarshal
		if err != nil {
			log.Fatal(err)
		}
		// Single path
		path := m.PathForKeyShortest("avg01")
		val, err := m.ValueForPath(path)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(val)
		// Multi-path
		paths := m.PathsForKey("percent")
		for _, path := range paths {
			val, err := m.ValueForPath(path)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Println(val)
		}
		io.WriteString(w, "Success")
	}
}
开发者ID:kkirsche,项目名称:monitCollector,代码行数:32,代码来源:collector.go

示例12: ParseRequest

func (as *AuthServer) ParseRequest(req *http.Request) (*AuthRequest, error) {
	ar := &AuthRequest{RemoteAddr: req.RemoteAddr}
	ar.ai.IP = parseRemoteAddr(req.RemoteAddr)
	if ar.ai.IP == nil {
		return nil, fmt.Errorf("unable to parse remote addr %s", req.RemoteAddr)
	}
	user, password, haveBasicAuth := req.BasicAuth()
	glog.V(3).Infof("user : %s, password : %s, haveBasicAuth : %v", user, password, haveBasicAuth)
	if haveBasicAuth {
		ar.User = user
		ar.Password = authn.PasswordString(password)
	}
	ar.ai.Account = req.FormValue("account")
	if ar.ai.Account == "" {
		ar.ai.Account = ar.User
	} else if haveBasicAuth && ar.ai.Account != ar.User {
		return nil, fmt.Errorf("user and account are not the same (%q vs %q)", ar.User, ar.ai.Account)
	}
	ar.ai.Service = req.FormValue("service")
	scope := req.FormValue("scope")
	if scope != "" {
		parts := strings.Split(scope, ":")
		if len(parts) != 3 {
			return nil, fmt.Errorf("invalid scope: %q", scope)
		}
		ar.ai.Type = parts[0]
		ar.ai.Name = parts[1]
		ar.ai.Actions = strings.Split(parts[2], ",")
		sort.Strings(ar.ai.Actions)
		glog.V(3).Infof("scope Type : %s, Name : %s, Actions : %s", ar.ai.Type, ar.ai.Name, ar.ai.Actions)
	}
	glog.V(3).Infoln("AuthServer :", ar)
	return ar, nil
}
开发者ID:firelyu,项目名称:docker_auth,代码行数:34,代码来源:server.go

示例13: getBasicAuthCredentials

func (s *service) getBasicAuthCredentials(r *http.Request) (email, username, password string) {
	if un, pw, ok := r.BasicAuth(); !ok {
		panic(s.ErrorsService.CreateHttpStatusClientError_Unauthorized("Unable to extract basic auth credentials"))
	} else {
		return un, un, pw
	}
}
开发者ID:francoishill,项目名称:golang-common-ddd,代码行数:7,代码来源:Service.go

示例14: homePage

func homePage(writer http.ResponseWriter, request *http.Request) {
	name, _, successAuth := request.BasicAuth()
	if !successAuth {
		writer.Header().Set("WWW-Authenticate", `Basic realm="protectedpage"`)
		http.Error(writer, "bad auth", http.StatusUnauthorized)
		return
	}
	writer.Header().Set("Content-type", "text/html")
	userPath := "cloud/usersStorage/" + name
	err := os.MkdirAll(userPath, 0777)
	if err != nil {
		log.Println(err, "problem with creating user's directory")
		http.Error(writer, "problen with user path", http.StatusBadRequest)
	}

	if reqSend := request.FormValue("sendButton"); reqSend != "" {
		uploadFile(request, userPath)
		showEntireFolder(writer, request, userPath, templt, name)
		return
	}
	if reqSend := request.FormValue("deleteButton"); reqSend != "" {
		slice, found := request.Form["option"]
		for i, _ := range slice {
			if err = deleteFile(slice[i], userPath); err != nil && found {
				http.Error(writer, "problem with deleting", http.StatusBadRequest)
			}
		}
		showEntireFolder(writer, request, userPath, templt, name)
		return
	}
	showEntireFolder(writer, request, userPath, templt, name)
}
开发者ID:vano144,项目名称:httpfileserver,代码行数:32,代码来源:main.go

示例15: ServeHTTP

// ServeHTTP allows Service to serve HTTP requests.
func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if s.credentialStore != nil {
		username, password, ok := r.BasicAuth()
		if !ok || !s.credentialStore.Check(username, password) {
			w.WriteHeader(http.StatusUnauthorized)
			return
		}
	}

	switch {
	case strings.HasPrefix(r.URL.Path, "/db/execute"):
		stats.Add(numExecutions, 1)
		s.handleExecute(w, r)
	case strings.HasPrefix(r.URL.Path, "/db/query"):
		stats.Add(numQueries, 1)
		s.handleQuery(w, r)
	case strings.HasPrefix(r.URL.Path, "/db/backup"):
		stats.Add(numBackups, 1)
		s.handleBackup(w, r)
	case strings.HasPrefix(r.URL.Path, "/join"):
		s.handleJoin(w, r)
	case strings.HasPrefix(r.URL.Path, "/status"):
		s.handleStatus(w, r)
	case r.URL.Path == "/debug/vars" && s.Expvar:
		serveExpvar(w, r)
	default:
		w.WriteHeader(http.StatusNotFound)
	}
}
开发者ID:GaobinWang,项目名称:rqlite,代码行数:30,代码来源:service.go


注:本文中的net/http.Request.BasicAuth方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。