Authenticates the API client by attaching an authenticator that signs requests.

@throws UnregisteredAuthenticatorException
14485
private function authenticate()
    {
        self::assertValidAuthType();

        $this->client
            ->getEmitter()
            ->attach(new $this->authenticators[$this->authType]($this));
    }
665014
protected void authenticateConnection (AuthingConnection conn)
    {
        Authenticator author = _author;
        for (ChainedAuthenticator cauthor : _authors) {
            if (cauthor.shouldHandleConnection(conn)) {
                author = cauthor;
                break;
            }
        }

        author.authenticateConnection(_authInvoker, conn, new ResultListener<AuthingConnection>() {
            public void requestCompleted (AuthingConnection conn) {
                _authq.append(conn);
            }
            public void requestFailed (Exception cause) {
                // this never happens
            }
        });
    }
928798
protected function authenticate()
    {
        // Check if the enough attributes have been set to perform authentication.
        // Note that password is not required by all methods.
        if (empty($this->username) || empty($this->authMethod)) {
            throw new ConfigurationException(
                sprintf(
                    'Missing authentication parameters. Method: "%s", username "%s".',
                    $this->authMethod,
                    $this->username
                )
            );
        }

        // Make sure a valid authentication method has been set.
        $authMethodMap = array(
            'http-token' => Client::AUTH_HTTP_TOKEN,
            'password' => Client::AUTH_HTTP_PASSWORD,
            'client-id' => Client::AUTH_URL_CLIENT_ID,
            'url-token' => Client::AUTH_URL_TOKEN,
        );
        if (!isset($authMethodMap[$this->authMethod])) {
            throw new ConfigurationException(
                sprintf(
                    'Unknown authentication method "%s". Supported methods "%s"',
                    $this->authMethod,
                    implode('", "', array_keys($authMethodMap))
                )
            );
        }

        // Set authentication.
        $this->client->authenticate($this->username, $this->password, $authMethodMap[$this->authMethod]);
    }
411521
@Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication == null) {
            return authentication;
        }
        UsernamePasswordAuthenticationToken output = null;
        if (authentication instanceof UsernamePasswordAuthenticationToken) {
            output = (UsernamePasswordAuthenticationToken) authentication;
        } else {
            output = new UsernamePasswordAuthenticationToken(authentication, authentication.getCredentials(),
                            authentication.getAuthorities());
            output.setAuthenticated(authentication.isAuthenticated());
            output.setDetails(authentication.getDetails());
        }
        return delegate.authenticate(output);
    }
1080118
def _not_authenticated(self):
        
        self._authenticator = None

        if api_settings.UNAUTHENTICATED_USER:
            self.user = api_settings.UNAUTHENTICATED_USER()
        else:
            self.user = None

        if api_settings.UNAUTHENTICATED_TOKEN:
            self.auth = api_settings.UNAUTHENTICATED_TOKEN()
        else:
            self.auth = None
224385
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Assert.isInstanceOf(SocialAuthenticationToken.class, authentication, "unsupported authentication type");
		Assert.isTrue(!authentication.isAuthenticated(), "already authenticated");
		SocialAuthenticationToken authToken = (SocialAuthenticationToken) authentication;
		String providerId = authToken.getProviderId();
		Connection<?> connection = authToken.getConnection();

		String userId = toUserId(connection);
		if (userId == null) {
			throw new BadCredentialsException("Unknown access token");
		}

		UserDetails userDetails = userDetailsService.loadUserByUserId(userId);
		if (userDetails == null) {
			throw new UsernameNotFoundException("Unknown connected account id");
		}

		return new SocialAuthenticationToken(connection, userDetails, authToken.getProviderAccountData(), getAuthorities(providerId, userDetails));
	}
756271
public function authenticate()
    {
        if (Configurator::AUTH_HTTP_TOKEN !== $this->configuration['authentication']['http-auth-type']) {
            throw new AdapterException('Authentication type for GitLab must be Token.');
        }

        $this->client->authenticate(
            $this->configuration['authentication']['password-or-token'],
            Client::AUTH_HTTP_TOKEN
        );

        return true;
    }
306745
public void authenticate(HttpURLConnection httpConn, String url) {
        String authorization = null;
        if (hasAccessToken() && isOperationOauth(url)) {
            logger.debug("Using OAuth token to authenticate");
            authorization = getAccessTokenType() + " " + getAccessToken();
        } else if (hasApiKey()) {
            logger.debug("Using API Key to authenticate");
            String apiKey = getApiKey() + ":";
            authorization = "Basic " + DatatypeConverter.printBase64Binary(apiKey.getBytes()).trim();
        }
        if (authorization != null) {
            logger.debug("Authorization: " + authorization);
            httpConn.setRequestProperty("authorization", authorization);
        }
    }
963980
def authenticate(self, client_id, client_secret, use_cache=True):
        
        # We will reuse a token for as long as we have one cached
        # and it hasn't expired.
        if use_cache:
            client = self._get_client_from_cache(client_id)
            if (client) and (not self.is_expired_token(client)):
                self.authenticated = True
                self.client = client
                return

        # Let's authenticate the client
        client = {
            'id': client_id,
            'secret': client_secret
        }

        res = self._authenticate_client(client_id, client_secret)
        client.update(res)

        expires = datetime.datetime.now() + \
                  datetime.timedelta(seconds=res['expires_in'])
        client['expires'] = expires.isoformat()

        # Cache it for repeated use until expired
        self._write_to_uaa_cache(client)

        self.client = client
        self.authenticated = True
11981
public function authenticate()
    {
        if (static::AUTH_METHOD_NOT_SET === $this->options['authmethod']) {
            $this->detectAuthMethod();
        }

        switch ($this->options['authmethod']) {
            case static::AUTH_METHOD_NULL:
                $this->executeCommand('AUTHENTICATE');
                break;

            case static::AUTH_METHOD_HASHEDPASSWORD:
                $password = $this->getOption('password');
                if (false === $password) {
                    throw new \Exception('You must set a password option');
                }

                $this->executeCommand('AUTHENTICATE '.static::quote($password));
                break;

            case static::AUTH_METHOD_COOKIE:
                $cookieFile = $this->getOption('cookiefile');
                if (false === $cookieFile) {
                    throw new \Exception('You must set a cookiefile option');
                }
                $cookie = file_get_contents($cookieFile);

                $this->executeCommand('AUTHENTICATE '.bin2hex($cookie));
                break;
        }

        return $this;
    }
689644
protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
    SignatureSecret secret = authentication.getConsumerDetails().getSignatureSecret();
    String token = authentication.getConsumerCredentials().getToken();
    OAuthProviderToken authToken = null;
    if (token != null && !"".equals(token)) {
      authToken = getTokenServices().getToken(token);
    }

    String signatureMethod = authentication.getConsumerCredentials().getSignatureMethod();
    OAuthSignatureMethod method;
    try {
      method = getSignatureMethodFactory().getSignatureMethod(signatureMethod, secret, authToken != null ? authToken.getSecret() : null);
    }
    catch (UnsupportedSignatureMethodException e) {
      throw new OAuthException(e.getMessage(), e);
    }

    String signatureBaseString = authentication.getConsumerCredentials().getSignatureBaseString();
    String signature = authentication.getConsumerCredentials().getSignature();
    if (log.isDebugEnabled()) {
      log.debug("Verifying signature " + signature + " for signature base string " + signatureBaseString + " with method " + method.getName() + ".");
    }
    method.verify(signatureBaseString, signature);
  }
1073817
private AuthenticationInfo getUncachedAuthenticationInfoForKey(String authenicationId) {
        ApiKey apiKey = _authIdentityReader.getIdentityByAuthenticationId(authenicationId);
        if (apiKey == null) {
            return null;
        }

        return createAuthenticationInfo(authenicationId, apiKey);
    }
372995
@Override
    @Transactional(value = "transactionManager", readOnly = true)
    public Authentication authenticate(Authentication authentication)
        throws AuthenticationException {

        // prepare an exception
        final String exceptionMessage = "User and password do not match.";

        // get username/password
        String accountName = authentication.getName();
        String rawPassword = (String) authentication.getCredentials();

        LOG.debug("Trying to authenticate User '" + accountName + "'");

        User user = userDao.findByAccountName(accountName);

        // prepare set of authorities
        Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();

        String encryptedPassword = null;

        if (user == null) {
            LOG.warn("No user for account name '" + accountName + "' could be found.");
            throw new UsernameNotFoundException(exceptionMessage);
        } else if (!user.isActive()) {
            LOG.warn("The user with the account name '" + accountName + "' is not active.");
            throw new DisabledException(exceptionMessage);
        } else {

            encryptedPassword = user.getPassword();

            // check if rawPassword matches the hash from db
            if (passwordEncoder.matches(rawPassword, encryptedPassword)) {

                Set<Role> allUserRoles = getAllUserRoles(user);

                // create granted authorities for the security context
                for (Role role : allUserRoles) {
                    grantedAuthorities.add(new SimpleGrantedAuthority(role.getName()));
                }

            } else {
                LOG.warn("The given password for user '" + accountName + "' does not match.");
                throw new BadCredentialsException(exceptionMessage);
            }

        }

        // Create corresponding token to forward in Spring Security's filter
        // chain. We will use the SHOGun-Core user as the principal.
        Authentication authResult = null;
        if (grantedAuthorities.isEmpty()) {
            // if the user has no authorities, we will build the
            // UsernamePasswordAuthenticationToken without authorities, which
            // leads to an unauthenticated user, i.e. isAuthenticated() of
            // authenticationToken will return false afterwards.
            LOG.warn("The user '" + accountName + "' has no authorities and will thereby NOT be authenticated.");
            authResult = new UsernamePasswordAuthenticationToken(user, encryptedPassword);
        } else {
            // if we pass some grantedAuthorities, isAuthenticated() of
            // authenticationToken will return true afterwards
            authResult = new UsernamePasswordAuthenticationToken(user, encryptedPassword, grantedAuthorities);

            LOG.debug("The user '" + accountName
                + "' got the following (explicit) roles: "
                + StringUtils.join(getRawRoleNames(grantedAuthorities), ", "));
        }

        final boolean isAuthenticated = authResult.isAuthenticated();
        final String authLog = isAuthenticated ? "has succesfully" : "has NOT";
        LOG.info("The user '" + accountName + "' " + authLog + " been authenticated.");

        return authResult;
    }
1281541
private function authenticateWithPassword()
    {
        if ($this->credentials->havePassword()) {
            $authCommand = new Auth();
            $authCommand->setArguments([$this->credentials->getPassword()]);
            $authResponse = $this->connection->execute($authCommand);
            $response = $authCommand->parse($authResponse);
            if ($response !== self::AUTH_SUCCESS_MESSAGE) {
                throw new AuthenticationException();
            }
        }
    }
1154974
public boolean authenticate(HttpServletRequest request) throws MnoException {
		String authHeader = request.getHeader("Authorization");
		if (authHeader == null || authHeader.isEmpty()) {
			return false;
		}
		String[] auth = authHeader.trim().split("\\s+");

		if (auth == null || auth.length != 2 || !auth[0].equalsIgnoreCase("basic")) {
			return false;
		}
		byte[] decodedStr = DatatypeConverter.parseBase64Binary(auth[1]);
		String[] creds;
		try {
			creds = (new String(decodedStr, "UTF-8")).split(":");
		} catch (UnsupportedEncodingException e) {
			throw new MnoException("Could not decode basic authentication" + Arrays.toString(auth), e);
		}

		if (creds.length == 2) {
			return authenticate(creds[0], creds[1]);
		} else {
			return false;
		}
	}
1044974
private function assertValidAuthType()
    {
        if (
            !array_key_exists($this->authType, $this->authenticators)
            || !class_exists($this->authenticators[$this->authType])
            || !is_subclass_of($this->authenticators[$this->authType], AbstractAuthenticator::class)
        ) {
            throw new UnregisteredAuthenticatorException(
                $this->authType . ' is not a registered authentication type'
            );
        }
    }
985258
def authenticate(api_key, api_url, **kwargs):
    """"""

    muddle = Muddle(**kwargs)

    # Login.
    muddle.authenticate(api_key, api_url)
    return muddle