Tries the next authentication method or raises a failure if all mechanisms
        have been tried.
172174
def authTryNextMethod(self):
        
        if not self.authOrder:
            raise DBusAuthenticationFailed()
        
        self.authMech  = self.authOrder.pop()
            
        if self.authMech == 'DBUS_COOKIE_SHA1':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify(getpass.getuser()))
        elif self.authMech == 'ANONYMOUS':
            self.sendAuthMessage('AUTH ' + self.authMech + ' ' +
                                 hexlify("txdbus"))
        else:
            self.sendAuthMessage('AUTH ' + self.authMech)
1129811
def _Verify(self):
    

    # If the list of expected calls is not empty, raise an exception
    if self._expected_calls_queue:
      # The last MultipleTimesGroup is not popped from the queue.
      if (len(self._expected_calls_queue) == 1 and
          isinstance(self._expected_calls_queue[0], MultipleTimesGroup) and
          self._expected_calls_queue[0].IsSatisfied()):
        pass
      else:
        raise ExpectedMethodCallsError(self._expected_calls_queue)
1234556
private static boolean isValidChallenge(String authenticateHeader, String authChallengePrefix) {
        if (authenticateHeader != null && !authenticateHeader.isEmpty()
                && authenticateHeader.toLowerCase().startsWith(authChallengePrefix.toLowerCase())) {
            return true;
        }
        return false;
    }
436540
private function detectAuthMethod()
    {
        $data = $this->executeCommand('PROTOCOLINFO');

        foreach ($data as $info) {
            if ('AUTH METHODS=NULL' === $info['message']) {
                $this->options['authmethod'] = static::AUTH_METHOD_NULL;

                return;
            }

            if ('AUTH METHODS=HASHEDPASSWORD' === $info['message']) {
                $this->options['authmethod'] = static::AUTH_METHOD_HASHEDPASSWORD;

                return;
            }

            if (preg_match('/^AUTH METHODS=(.*) COOKIEFILE="(.*)"/', $info['message'], $matches) === 1) {
                $this->options['authmethod'] = static::AUTH_METHOD_COOKIE;
                $this->options['cookiefile'] = $matches[2];

                return;
            }
        }

        throw new Exception\ProtocolError('Auth method not supported');
    }
277979
protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
            SecurityProviderException, IOException {
        Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
        // If user is anonymous, authentication is required
        if (auth == null) {
            try {
                // Throw ex just to initialize stack trace
                throw new AuthenticationRequiredException("Authentication required to access the resource", e);
            } catch (AuthenticationRequiredException ae) {
                logger.debug("Authentication is required", ae);

                authenticationRequiredHandler.handle(context, ae);
            }
        } else {
            logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e);

            accessDeniedHandler.handle(context, e);
        }
    }
60747
def do_authentication(environ, start_response, authn_context, key,
                      redirect_uri):
    
    logger.debug("Do authentication")
    auth_info = AUTHN_BROKER.pick(authn_context)

    if len(auth_info):
        method, reference = auth_info[0]
        logger.debug("Authn chosen: %s (ref=%s)", method, reference)
        return method(environ, start_response, reference, key, redirect_uri)
    else:
        resp = Unauthorized("No usable authentication method")
        return resp(environ, start_response)
81248
public void assertAuthFail(byte[] expectedSignature, BuilderMode builderMode, String errorMessage) {
        if (isHashEquals(expectedSignature, builderMode)) {
            if (Validator.isEmpty(errorMessage)) {
                throw new IllegalArgumentException();
            } else {
                throw new IllegalArgumentException(errorMessage);
            }
        }
    }
1028598
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'token':
            return None

        if len(auth) == 1:
            msg = _('Invalid auth token header. No credentials provided.')
            raise AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        try:
            token = urlsafe_b64decode(auth[1])
        except ValueError:
            msg = _('Invalid auth token.')
            raise AuthenticationFailed(msg)

        return self.authenticate_credentials(token, request)
448586
def _check_error_response(self, response, context):
        
        if "error" in response:
            satosa_logging(logger, logging.DEBUG, "%s error: %s %s" %
                           (type(response).__name__, response["error"], response.get("error_description", "")),
                           context.state)
            raise SATOSAAuthenticationError(context.state, "Access denied")
1184392
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;
		User user = null;

		if (requestURI.endsWith(OPENID_ACTION)) {
			Authentication oidAuth = super.attemptAuthentication(request, response);

			if (oidAuth == null) {
				// hang on... redirecting to openid provider
				return null;
			} else {
				//success!
				AuthenticatedUserDetails userDetails = (AuthenticatedUserDetails) oidAuth.getPrincipal();
				userAuth = new UserAuthentication(userDetails);
				user = userDetails.getUser();
			}
		}

		return SecurityUtils.checkIfActive(userAuth, user, true);
	}
1290711
def handle_other(self, response):
        """"""

        log.debug("handle_other(): Handling: %d" % response.status_code)

        if self.mutual_authentication in (REQUIRED, OPTIONAL) and not self.auth_done:

            is_http_error = response.status_code >= 400

            if _negotiate_value(response) is not None:
                log.debug("handle_other(): Authenticating the server")
                if not self.authenticate_server(response):
                    # Mutual authentication failure when mutual auth is wanted,
                    # raise an exception so the user doesn't use an untrusted
                    # response.
                    log.error("handle_other(): Mutual authentication failed")
                    raise MutualAuthenticationError("Unable to authenticate "
                                                    "{0}".format(response))

                # Authentication successful
                log.debug("handle_other(): returning {0}".format(response))
                self.auth_done = True
                return response

            elif is_http_error or self.mutual_authentication == OPTIONAL:
                if not response.ok:
                    log.error("handle_other(): Mutual authentication unavailable "
                              "on {0} response".format(response.status_code))

                if(self.mutual_authentication == REQUIRED and
                       self.sanitize_mutual_error_response):
                    return SanitizedResponse(response)
                else:
                    return response
            else:
                # Unable to attempt mutual authentication when mutual auth is
                # required, raise an exception so the user doesn't use an
                # untrusted response.
                log.error("handle_other(): Mutual authentication failed")
                raise MutualAuthenticationError("Unable to authenticate "
                                                "{0}".format(response))
        else:
            log.debug("handle_other(): returning {0}".format(response))
            return response
186990
def authentication_validation(username, password, access_token):
    '''
    
    '''
    if bool(username) is not bool(password):
        raise Exception("Basic authentication requires a username AND"
                        " password.")
    if (username and access_token) or (password and access_token):
        raise Exception("Cannot use both Basic Authentication and"
                        " OAuth2.0. Please use only one authentication"
                        " method.")
117691
def authenticate(self, password):
        
        user = None

        try:
            self._authenticate_user_dn(password)
            self._check_requirements()
            self._get_or_create_user()

            user = self._user
        except self.AuthenticationFailed as e:
            logger.debug(u"Authentication failed for %s: %s" % (self._username, e))
        except ldap.LDAPError as e:
            results = ldap_error.send(self.backend.__class__,
                                      context='authenticate', exception=e)
            if len(results) == 0:
                logger.warning(u"Caught LDAPError while authenticating %s: %s",
                               self._username, pprint.pformat(e))
        except Exception:
            logger.exception(u"Caught Exception while authenticating %s",
                             self._username)
            raise

        return user
988741
def _auth_required(method, validator):
    
    @gen.coroutine
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        token = _get_token(self.request)
        valid_token = yield validator(token)
        if not valid_token:
            message = 'Invalid token: {}'.format(token)
            logging.warning(message)
            raise HTTPError(401, message)
        result = method(self, *args, **kwargs)

        if isinstance(result, Future):
            result = yield result

        raise gen.Return(result)

    return wrapper
1133354
public function handle(Request $request, Closure $next)
    {
        if ($this->auth->guard('wink')->check()) {
            $this->auth->shouldUse('wink');
        } else {
            throw new AuthenticationException(
                'Unauthenticated.', ['wink'], route('wink.auth.login')
            );
        }

        return $next($request);
    }
826120
def add_auth_attempt(self, auth_type, successful, **kwargs):
        

        entry = {'timestamp': datetime.utcnow(),
                 'auth': auth_type,
                 'id': uuid.uuid4(),
                 'successful': successful}

        log_string = ''
        for key, value in kwargs.iteritems():
            if key == 'challenge' or key == 'response':
                entry[key] = repr(value)
            else:
                entry[key] = value
                log_string += '{0}:{1}, '.format(key, value)

        self.login_attempts.append(entry)
431672
def authenticate!
      if u = user_class.send(config[:authenticate_method], *required_param_values)
        success!(u)
      else
        fail!(config[:error_message])
      end
    end