// authenticate forces authentication set by RegisterDefaultAuth.
6626
func (s *Server) authenticate() router.Middleware {
	a := s.Authenticator
	if a == nil {
		a = GetDefaultAuth()
		if a == nil {
			panic("prpc: no custom Authenticator was provided and default authenticator was not registered.\n" +
				"Either explicitly set `Server.Authenticator = NoAuthentication`, or use RegisterDefaultAuth()")
		}
	}

	return func(c *router.Context, next router.Handler) {
		switch ctx, err := a.Authenticate(c.Context, c.Request); {
		case transient.Tag.In(err):
			writeError(c.Context, c.Writer, withCode(err, codes.Internal))
		case err != nil:
			writeError(c.Context, c.Writer, withCode(err, codes.Unauthenticated))
		default:
			c.Context = ctx
			next(c)
		}
	}
}
1141123
func (c *Client) AuthenticateHost(hostID string) (string, int64, error) {
	req := HostAuthenticationRequest{
		HostID:    hostID,
		Timestamp: time.Now().UTC().Unix(),
	}
	sig, err := auth.SignAsDelegate(req.toMessage())
	if err != nil {
		return "", 0, err
	}
	req.Signature = sig
	var response HostAuthenticationResponse
	if err := c.call("AuthenticateHost", req, &response); err != nil {
		return "", 0, err
	}
	return response.Token, response.Expires, nil
}
758520
func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
	err := validate(key)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	perms, err := c.CertChecker.Authenticate(conn, key)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	return perms, nil
}
444044
func (identityStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
	identity := obj.(*userapi.Identity)
	return validation.ValidateIdentity(identity)
}
22850
func (a authenticator) Authenticate(
	entityFinder authentication.EntityFinder,
	tag names.Tag,
	req params.LoginRequest,
) (state.Entity, error) {
	auth, err := a.authenticatorForTag(tag)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return auth.Authenticate(entityFinder, tag, req)
}
227674
func (m *Swaggeroauth2TokenParameters) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateGrantType(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	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
}
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)
}
844032
func (d *DummyMailstore) Authenticate(username string, password string) (User, error) {
	if username != "username" {
		return &DummyUser{}, errors.New("Invalid username. Use 'username'")
	}

	if password != "password" {
		return &DummyUser{}, errors.New("Invalid password. Use 'password'")
	}

	d.User.authenticated = true
	return d.User, nil
}
744160
func (ra *RouteAuthenticator) Authenticate(req *http.Request, route *MatchedRoute) (bool, interface{}, error) {
	if ra.allowAnonymous {
		route.Authenticator = ra
		return true, nil, nil
	}
	// iterate in proper order
	var lastResult interface{}
	for _, scheme := range ra.Schemes {
		if authenticator, ok := ra.Authenticator[scheme]; ok {
			applies, princ, err := authenticator.Authenticate(&security.ScopedAuthRequest{
				Request:        req,
				RequiredScopes: ra.Scopes[scheme],
			})
			if !applies {
				return false, nil, nil
			}
			if err != nil {
				route.Authenticator = ra
				return true, nil, err
			}
			lastResult = princ
		}
	}
	route.Authenticator = ra
	return true, lastResult, nil
}
1134657
func (c *Connection) authenticated() bool {
	if c.StorageUrl == "" || c.AuthToken == "" {
		return false
	}
	if c.Expires.IsZero() {
		return true
	}
	timeUntilExpiry := c.Expires.Sub(time.Now())
	return timeUntilExpiry >= 60*time.Second
}
101367
func (m *SwaggerRevokeOAuth2TokenParameters) Validate(formats strfmt.Registry) error {
	var res []error

	if err := m.validateToken(formats); err != nil {
		res = append(res, err)
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}
781159
func (a *ArgoCDServer) authenticate(ctx context.Context) (context.Context, error) {
	if a.DisableAuth {
		return ctx, nil
	}
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		return ctx, ErrNoSession
	}
	tokenString := getToken(md)
	if tokenString == "" {
		return ctx, ErrNoSession
	}
	claims, err := a.sessionMgr.VerifyToken(tokenString)
	if err != nil {
		return ctx, status.Errorf(codes.Unauthenticated, "invalid session: %v", err)
	}
	// Add claims to the context to inspect for RBAC
	ctx = context.WithValue(ctx, "claims", claims)
	return ctx, 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
}
362621
func (context *APIContext) Authentication(request *restful.Request) (interface{}, error) {
	//FIXME: implement this properly

	t := request.QueryParameter("accesstoken")
	if len(t) == 0 {
		t = request.HeaderParameter("authorization")
		if strings.Index(t, " ") > 0 {
			t = strings.TrimSpace(strings.Split(t, " ")[1])
		}
	}

	return nil, nil // context.GetUserByAccessToken(t)
}
1007017
func (client Client) Authenticate(creds map[string]string, origin string, grantType constant.GrantType) (string, string, error) {
	requestBody := url.Values{
		"grant_type": {string(grantType)},
	}

	for k, v := range creds {
		requestBody.Set(k, v)
	}

	type loginHint struct {
		Origin string `json:"origin"`
	}

	originStruct := loginHint{origin}
	originParam, err := json.Marshal(originStruct)
	if err != nil {
		return "", "", err
	}

	var query url.Values
	if origin != "" {
		query = url.Values{
			"login_hint": {string(originParam)},
		}
	}

	request, err := client.newRequest(requestOptions{
		RequestName: internal.PostOAuthTokenRequest,
		Header: http.Header{
			"Content-Type": {"application/x-www-form-urlencoded"},
		},
		Body:  strings.NewReader(requestBody.Encode()),
		Query: query,
	})

	if err != nil {
		return "", "", err
	}

	if grantType == constant.GrantTypePassword {
		request.SetBasicAuth(client.config.UAAOAuthClient(), client.config.UAAOAuthClientSecret())
	}

	responseBody := AuthResponse{}
	response := Response{
		Result: &responseBody,
	}

	err = client.connection.Make(request, &response)
	return responseBody.AccessToken, responseBody.RefreshToken, err
}
1322735
func (context *Context) Authentication(request *restful.Request) (interface{}, error) {
	return nil, errors.New("Auth is not implemented")
}