本文整理汇总了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)
}
示例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
}
示例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
}
示例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
}
示例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")
}
示例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()
}
}
示例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"))
}
示例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)
}
示例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
}
}
示例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
}
}
示例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")
}
}
示例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
}
示例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
}
}
示例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)
}
示例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)
}
}