// Authenticate authenticates the request using the named strategy, and returns
// a new context.Context with the user embedded. The user can be retrieved with
// UserFromContext.
973383
func (a *Auth) Authenticate(ctx context.Context, username, password, otp string, strategies ...string) (context.Context, error) {
	// Default to using all strategies to authenticate.
	authenticator := a.Strategies.AuthenticatorFor(strategies...)
	return a.authenticate(ctx, authenticator, username, password, otp)
}
204247
func (c *VAClient) Authenticate(username, password, computeid, vdcid string) (Vdc, error) {
	// Authorize
	vaservicehref, err := c.vaauthorize(username, password)
	if err != nil {
		return Vdc{}, fmt.Errorf("error Authorizing: %s", err)
	}

	// Get Service
	vacomputehref, err := c.vaacquireservice(vaservicehref, computeid)
	if err != nil {
		return Vdc{}, fmt.Errorf("error Acquiring Service: %s", err)
	}

	// Get Compute
	vavdchref, err := c.vaacquirecompute(vacomputehref, vdcid)
	if err != nil {
		return Vdc{}, fmt.Errorf("error Acquiring Compute: %s", err)
	}

	// Get Backend Authorization
	if err = c.vagetbackendauth(vavdchref, computeid); err != nil {
		return Vdc{}, fmt.Errorf("error Acquiring Backend Authorization: %s", err)
	}

	v, err := c.Client.retrieveVDC()
	if err != nil {
		return Vdc{}, fmt.Errorf("error Acquiring VDC: %s", err)
	}

	return v, nil

}
629845
func (*denyAuthenticator) AuthenticateClient(client api.Client) (*authenticator.Response, bool, error) {
	return nil, false, nil
}
514165
func (b *basicAuth) authenticate(r *http.Request) bool {
	const basicScheme string = "Basic "

	if r == nil {
		return false
	}

	// In simple mode, prevent authentication with empty credentials if User is
	// not set. Allow empty passwords to support non-password use-cases.
	if b.opts.AuthFunc == nil && b.opts.User == "" {
		return false
	}

	// Confirm the request is sending Basic Authentication credentials.
	auth := r.Header.Get("Authorization")
	if !strings.HasPrefix(auth, basicScheme) {
		return false
	}

	// Get the plain-text username and password from the request.
	// The first six characters are skipped - e.g. "Basic ".
	str, err := base64.StdEncoding.DecodeString(auth[len(basicScheme):])
	if err != nil {
		return false
	}

	// Split on the first ":" character only, with any subsequent colons assumed to be part
	// of the password. Note that the RFC2617 standard does not place any limitations on
	// allowable characters in the password.
	creds := bytes.SplitN(str, []byte(":"), 2)

	if len(creds) != 2 {
		return false
	}

	givenUser := string(creds[0])
	givenPass := string(creds[1])

	// Default to Simple mode if no AuthFunc is defined.
	if b.opts.AuthFunc == nil {
		b.opts.AuthFunc = b.simpleBasicAuthFunc
	}

	return b.opts.AuthFunc(givenUser, givenPass, r)
}
870884
func authenticate(c *vaultapi.Client, authType string, params map[string]string) (err error) {
	var secret *vaultapi.Secret

	// handle panics gracefully by creating an error
	// this would happen when we get a parameter that is missing
	defer panicToError(&err)

	path := params["path"]
	if path == "" {
		path = authType
		if authType == "app-role" {
			path = "approle"
		}
	}
	url := fmt.Sprintf("/auth/%s/login", path)

	switch authType {
	case "app-role":
		secret, err = c.Logical().Write(url, map[string]interface{}{
			"role_id":   getParameter("role-id", params),
			"secret_id": getParameter("secret-id", params),
		})
	case "app-id":
		secret, err = c.Logical().Write(url, map[string]interface{}{
			"app_id":  getParameter("app-id", params),
			"user_id": getParameter("user-id", params),
		})
	case "github":
		secret, err = c.Logical().Write(url, map[string]interface{}{
			"token": getParameter("token", params),
		})
	case "token":
		c.SetToken(getParameter("token", params))
		secret, err = c.Logical().Read("/auth/token/lookup-self")
	case "userpass":
		username, password := getParameter("username", params), getParameter("password", params)
		secret, err = c.Logical().Write(fmt.Sprintf("%s/%s", url, username), map[string]interface{}{
			"password": password,
		})
	case "kubernetes":
		jwt, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/token")
		if err != nil {
			return err
		}
		secret, err = c.Logical().Write(url, map[string]interface{}{
			"jwt":  string(jwt[:]),
			"role": getParameter("role-id", params),
		})
	case "cert":
		secret, err = c.Logical().Write(url, map[string]interface{}{})
	}

	if err != nil {
		return err
	}

	// if the token has already been set
	if c.Token() != "" {
		return nil
	}

	if secret == nil || secret.Auth == nil {
		return errors.New("Unable to authenticate")
	}

	log.Debug("client authenticated with auth backend: %s", authType)
	// the default place for a token is in the auth section
	// otherwise, the backend will set the token itself
	c.SetToken(secret.Auth.ClientToken)
	return nil
}
293213
func (c *Connection) authenticate() (err error) {
	c.setDefaults()

	// Flush the keepalives connection - if we are
	// re-authenticating then stuff has gone wrong
	flushKeepaliveConnections(c.Transport)

	if c.Auth == nil {
		c.Auth, err = newAuth(c)
		if err != nil {
			return
		}
	}

	retries := 1
again:
	var req *http.Request
	req, err = c.Auth.Request(c)
	if err != nil {
		return
	}
	if req != nil {
		timer := time.NewTimer(c.ConnectTimeout)
		defer timer.Stop()
		var resp *http.Response
		resp, err = c.doTimeoutRequest(timer, req)
		if err != nil {
			return
		}
		defer func() {
			drainAndClose(resp.Body, &err)
			// Flush the auth connection - we don't want to keep
			// it open if keepalives were enabled
			flushKeepaliveConnections(c.Transport)
		}()
		if err = c.parseHeaders(resp, authErrorMap); err != nil {
			// Try again for a limited number of times on
			// AuthorizationFailed or BadRequest. This allows us
			// to try some alternate forms of the request
			if (err == AuthorizationFailed || err == BadRequest) && retries > 0 {
				retries--
				goto again
			}
			return
		}
		err = c.Auth.Response(resp)
		if err != nil {
			return
		}
	}
	if customAuth, isCustom := c.Auth.(CustomEndpointAuthenticator); isCustom && c.EndpointType != "" {
		c.StorageUrl = customAuth.StorageUrlForEndpoint(c.EndpointType)
	} else {
		c.StorageUrl = c.Auth.StorageUrl(c.Internal)
	}
	c.AuthToken = c.Auth.Token()
	if do, ok := c.Auth.(Expireser); ok {
		c.Expires = do.Expires()
	} else {
		c.Expires = time.Time{}
	}

	if !c.authenticated() {
		err = newError(0, "Response didn't have storage url and auth token")
		return
	}
	return
}
678165
func (ctxt *authContext) authenticator(serverHost string) authenticator {
	return authenticator{ctxt: ctxt, serverHost: serverHost}
}
826448
func (strategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	roleBinding := obj.(*rbac.RoleBinding)
	return validation.ValidateRoleBinding(roleBinding)
}
75545
func (s *AuthServer) AuthenticateUser(req AuthenticateUserRequest) error {
	err := s.authenticateUser(req)
	if err != nil {
		s.EmitAuditEvent(events.UserLocalLoginFailure, events.EventFields{
			events.EventUser:          req.Username,
			events.LoginMethod:        events.LoginMethodLocal,
			events.AuthAttemptSuccess: false,
			events.AuthAttemptErr:     err.Error(),
		})
	} else {
		s.EmitAuditEvent(events.UserLocalLogin, events.EventFields{
			events.EventUser:          req.Username,
			events.LoginMethod:        events.LoginMethodLocal,
			events.AuthAttemptSuccess: true,
		})
	}
	return err
}
1209127
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) {
	const accessDeniedMsg = "[00] access denied"

	var isRemoteUser bool
	userTypeI := req.Context().Value(auth.ContextUser)
	switch userTypeI.(type) {
	case auth.LocalUser:

	case auth.RemoteUser:
		isRemoteUser = true
	default:
		f.Warningf("Denying proxy access to unsupported user type: %T.", userTypeI)
		return nil, trace.AccessDenied(accessDeniedMsg)
	}

	userContext, err := f.Auth.Authorize(req.Context())
	if err != nil {
		switch {
		// propagate connection problem error so we can differentiate
		// between connection failed and access denied
		case trace.IsConnectionProblem(err):
			return nil, trace.ConnectionProblem(err, "[07] failed to connect to the database")
		case trace.IsAccessDenied(err):
			// don't print stack trace, just log the warning
			f.Warn(err)
			return nil, trace.AccessDenied(accessDeniedMsg)
		default:
			f.Warn(trace.DebugReport(err))
			return nil, trace.AccessDenied(accessDeniedMsg)
		}
	}
	peers := req.TLS.PeerCertificates
	if len(peers) > 1 {
		// when turning intermediaries on, don't forget to verify
		// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59
		return nil, trace.AccessDenied("access denied: intermediaries are not supported")
	}
	if len(peers) == 0 {
		return nil, trace.AccessDenied("access denied: only mutual TLS authentication is supported")
	}
	clientCert := peers[0]
	authContext, err := f.setupContext(*userContext, req, isRemoteUser, clientCert.NotAfter)
	if err != nil {
		f.Warn(err.Error())
		return nil, trace.AccessDenied(accessDeniedMsg)
	}
	return authContext, nil
}
82578
func (c *Client) Authenticate(ctx context.Context) (Response, error) {
	path := "/auth"
	req, _ := http.NewRequest("POST", c.baseURL+path, nil)
	c.authenticator.SetAuth(req)
	req.Header.Set("Content-Type", "application/json")

	c.authentication = Authentication{}

	body, resp, err := c.do(req.WithContext(ctx))
	if err != nil {
		return resp, err
	}

	var auth = &struct {
		Authentication
		Error string `json:"error,omitempty"`
	}{}

	if err = json.Unmarshal(body, auth); err != nil {
		return resp, errors.Wrap(err, "unable to unmarshal JSON")
	}

	if auth.Error != "" {
		return resp, toError(auth.Error)
	}

	c.authentication = auth.Authentication
	return resp, err
}
260713
func (a *api) authenticateHost() error {
	if hostAuthenticated {
		return nil
	}

	options := config.GetOptions()

	// Try to load the master keys, fail silently if they don't exist
	masterKeyFile := filepath.Join(options.IsvcsPath, auth.MasterKeyFileName)
	if err := auth.LoadMasterKeyFile(masterKeyFile); err != nil {
		log.WithError(err).Debug("Unable to load master keys")
	}

	// Load the delegate keys
	delegateKeyFile := filepath.Join(options.EtcPath, auth.DelegateKeyFileName)
	if err := auth.LoadDelegateKeysFromFile(delegateKeyFile); err != nil {
		return err
	}

	// Get our host ID
	myHostID, err := utils.HostID()
	if err != nil {
		return err
	} else if err := validation.ValidHostID(myHostID); err != nil {
		return err
	}

	// Load an auth token once
	tokenFile := filepath.Join(options.EtcPath, auth.TokenFileName)
	getToken := func() (string, int64, error) {
		return a.AuthenticateHost(myHostID)
	}

	if _, err := auth.RefreshToken(getToken, tokenFile); err != nil {
		return err
	}

	hostAuthenticated = true
	return nil
}
343331
func (s *AuthenticationService) Authenticated() bool {
	if s != nil {
		if s.authType == authTypeSession {
			return s.client.session != nil
		} else if s.authType == authTypeBasic {
			return s.username != ""
		}

	}
	return false
}
666329
func (e *ECU) authenticate(ctx *ipc.Context) (*ipc.Context, error) {
	return nil, errors.New("unimplemented")
}
1007322
func (f RequestFunc) AuthenticateRequest(req *http.Request) (*Response, bool, error) {
	return f(req)
}
155248
func (m *ExternalMacaroonAuthenticator) Authenticate(entityFinder EntityFinder, _ names.Tag, req params.LoginRequest) (state.Entity, error) {
	declared, err := m.Service.CheckAny(req.Macaroons, nil, checkers.New(checkers.TimeBefore))
	if _, ok := errors.Cause(err).(*bakery.VerificationError); ok {
		return nil, m.newDischargeRequiredError(err)
	}
	if err != nil {
		return nil, errors.Trace(err)
	}
	username := declared[usernameKey]
	var tag names.UserTag
	if names.IsValidUserName(username) {
		// The name is a local name without an explicit @local suffix.
		// In this case, for compatibility with 3rd parties that don't
		// care to add their own domain, we add an @external domain
		// to ensure there is no confusion between local and external
		// users.
		// TODO(rog) remove this logic when deployed dischargers
		// always add an @ domain.
		tag = names.NewLocalUserTag(username).WithDomain("external")
	} else {
		// We have a name with an explicit domain (or an invalid user name).
		if !names.IsValidUser(username) {
			return nil, errors.Errorf("%q is an invalid user name", username)
		}
		tag = names.NewUserTag(username)
		if tag.IsLocal() {
			return nil, errors.Errorf("external identity provider has provided ostensibly local name %q", username)
		}
	}
	entity, err := entityFinder.FindEntity(tag)
	if errors.IsNotFound(err) {
		return nil, errors.Trace(common.ErrBadCreds)
	} else if err != nil {
		return nil, errors.Trace(err)
	}
	return entity, nil
}
598663
func (fn AuthenticatorFunc) Authenticate(username, password, otp string) (*Session, error) {
	return fn(username, password, otp)
}