Authenticate using SCRAM.
10350
def _authenticate_scram(credentials, sock_info, mechanism):
    """"""

    username = credentials.username
    if mechanism == 'SCRAM-SHA-256':
        digest = "sha256"
        digestmod = hashlib.sha256
        data = saslprep(credentials.password).encode("utf-8")
    else:
        digest = "sha1"
        digestmod = hashlib.sha1
        data = _password_digest(username, credentials.password).encode("utf-8")
    source = credentials.source
    cache = credentials.cache

    # Make local
    _hmac = hmac.HMAC

    user = username.encode("utf-8").replace(b"=", b"=3D").replace(b",", b"=2C")
    nonce = standard_b64encode(os.urandom(32))
    first_bare = b"n=" + user + b",r=" + nonce

    cmd = SON([('saslStart', 1),
               ('mechanism', mechanism),
               ('payload', Binary(b"n,," + first_bare)),
               ('autoAuthorize', 1)])
    res = sock_info.command(source, cmd)

    server_first = res['payload']
    parsed = _parse_scram_response(server_first)
    iterations = int(parsed[b'i'])
    if iterations < 4096:
        raise OperationFailure("Server returned an invalid iteration count.")
    salt = parsed[b's']
    rnonce = parsed[b'r']
    if not rnonce.startswith(nonce):
        raise OperationFailure("Server returned an invalid nonce.")

    without_proof = b"c=biws,r=" + rnonce
    if cache.data:
        client_key, server_key, csalt, citerations = cache.data
    else:
        client_key, server_key, csalt, citerations = None, None, None, None

    # Salt and / or iterations could change for a number of different
    # reasons. Either changing invalidates the cache.
    if not client_key or salt != csalt or iterations != citerations:
        salted_pass = _hi(
            digest, data, standard_b64decode(salt), iterations)
        client_key = _hmac(salted_pass, b"Client Key", digestmod).digest()
        server_key = _hmac(salted_pass, b"Server Key", digestmod).digest()
        cache.data = (client_key, server_key, salt, iterations)
    stored_key = digestmod(client_key).digest()
    auth_msg = b",".join((first_bare, server_first, without_proof))
    client_sig = _hmac(stored_key, auth_msg, digestmod).digest()
    client_proof = b"p=" + standard_b64encode(_xor(client_key, client_sig))
    client_final = b",".join((without_proof, client_proof))

    server_sig = standard_b64encode(
        _hmac(server_key, auth_msg, digestmod).digest())

    cmd = SON([('saslContinue', 1),
               ('conversationId', res['conversationId']),
               ('payload', Binary(client_final))])
    res = sock_info.command(source, cmd)

    parsed = _parse_scram_response(res['payload'])
    if not compare_digest(parsed[b'v'], server_sig):
        raise OperationFailure("Server returned an invalid signature.")

    # Depending on how it's configured, Cyrus SASL (which the server uses)
    # requires a third empty challenge.
    if not res['done']:
        cmd = SON([('saslContinue', 1),
                   ('conversationId', res['conversationId']),
                   ('payload', Binary(b''))])
        res = sock_info.command(source, cmd)
        if not res['done']:
            raise OperationFailure('SASL conversation failed to complete.')
762919
def authenticate(self, password):
        """"""
        if self.isClosed:
            raise ValueError("operation illegal for closed doc")

        val = _fitz.Document_authenticate(self, password)

        if val: # the doc is decrypted successfully and we init the outline
            self.isEncrypted = 0
            self.initData()
            self.thisown = True


        return val
618148
def step1(self, username, password):
        """"""
        self._check_initialized()
        context = AtvSRPContext(
            str(username), str(password),
            prime=constants.PRIME_2048,
            generator=constants.PRIME_2048_GEN)
        self.session = SRPClientSession(
            context, binascii.hexlify(self._auth_private).decode())
697651
def authenticate(self) -> bool:
        """"""
        with IHCController._mutex:
            if not self.client.authenticate(self._username, self._password):
                return False
            if self._ihcevents:
                self.client.enable_runtime_notifications(
                    self._ihcevents.keys())
            return True
738639
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except MoparError:
            _LOGGER.info("attempted to access page before login")
            _login(args[0])
            return function(*args)
    return wrapped
846925
def authenticate(self, dn='', password=''):
        
        try:
            self.connection.simple_bind_s(dn, password)
        except tuple(self.failed_authentication_exceptions):
            return False
        else:
            return True
245414
def authenticate(self, user, password):
        """"""
        assert user['password_hash'] == '_'.join((password, 'hash'))
        self.logger.debug('User %s has been successfully authenticated',
                          user['uid'])
908822
def authenticationResponse():
    """"""
    a = TpPd(pd=0x5)
    b = MessageType(mesType=0x14)  # 00010100
    c = AuthenticationParameterSRES()
    packet = a / b / c
    return packet
471789
def authenticate(self, req, resp, resource):
        
        payload = self._decode_jwt_token(req)
        user = self.user_loader(payload)
        if not user:
            raise falcon.HTTPUnauthorized(
                description='Invalid JWT Credentials')

        return user
17058
def authenticate_with_access_token(access_token):
    """"""
    credentials = Credentials(access_token=access_token)
    client = YamcsClient('localhost:8090', credentials=credentials)

    for link in client.list_data_links('simulator'):
        print(link)
512960
def authenticate(self):
        
        if self._auth_token is None or self._token_expiry < time.time():
            self._perform_auth()

        yield self._auth_token
28722
def authenticate(self, retries=3):
        

        username = self.username or self._getuser(self.base)
        password = self.password

        while retries > 0:
            if password is None:
                password = self._getpass(self.base, username)

            try:
                resp = self.post(self.base+'/authenticate', params={'username': username, 'password': password})

                schema = UserSchema()
                u = self.decode(schema, resp)

                if u.token is not None:
                    self.lock.acquire()
                    self.token = u.token
                    self.lock.release()
                    break
            except CDRouterError as cde:
                password = None
                retries -= 1
                if retries == 0:
                    raise cde

        return self.token
1160210
def authenticated(function):
    """"""
    def wrapped(session, *args, **kwargs):
        """Wrap function."""
        try:
            return function(session, *args, **kwargs)
        except VooblyError:
            with session.cache_disabled():
                _LOGGER.info("attempted to access page before login")
                login(session)
                return function(session, *args, **kwargs)
    return wrapped
533320
public void authenticate() {
        URL url;
        try {
            url = new URL(this.getTokenURL());
        } catch (MalformedURLException e) {
            assert false : "An invalid token URL indicates a bug in the SDK.";
            throw new RuntimeException("An invalid token URL indicates a bug in the SDK.", e);
        }

        String jwtAssertion = this.constructJWTAssertion();

        String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

        BoxAPIRequest request = new BoxAPIRequest(this, url, "POST");
        request.shouldAuthenticate(false);
        request.setBody(urlParameters);

        String json;
        try {
            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        } catch (BoxAPIException ex) {
            // Use the Date advertised by the Box server as the current time to synchronize clocks
            List<String> responseDates = ex.getHeaders().get("Date");
            NumericDate currentTime;
            if (responseDates != null) {
                String responseDate = responseDates.get(0);
                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
                try {
                    Date date = dateFormat.parse(responseDate);
                    currentTime = NumericDate.fromMilliseconds(date.getTime());
                } catch (ParseException e) {
                    currentTime = NumericDate.now();
                }
            } else {
                currentTime = NumericDate.now();
            }

            // Reconstruct the JWT assertion, which regenerates the jti claim, with the new "current" time
            jwtAssertion = this.constructJWTAssertion(currentTime);
            urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);

            // Re-send the updated request
            request = new BoxAPIRequest(this, url, "POST");
            request.shouldAuthenticate(false);
            request.setBody(urlParameters);

            BoxJSONResponse response = (BoxJSONResponse) request.send();
            json = response.getJSON();
        }

        JsonObject jsonObject = JsonObject.readFrom(json);
        this.setAccessToken(jsonObject.get("access_token").asString());
        this.setLastRefresh(System.currentTimeMillis());
        this.setExpires(jsonObject.get("expires_in").asLong() * 1000);

        //if token cache is specified, save to cache
        if (this.accessTokenCache != null) {
            String key = this.getAccessTokenCacheKey();
            JsonObject accessTokenCacheInfo = new JsonObject()
                    .add("accessToken", this.getAccessToken())
                    .add("lastRefresh", this.getLastRefresh())
                    .add("expires", this.getExpires());

            this.accessTokenCache.put(key, accessTokenCacheInfo.toString());
        }
    }
75387
def www_authenticate(self):
        """"""
        def on_update(www_auth):
            if not www_auth and 'www-authenticate' in self.headers:
                del self.headers['www-authenticate']
            elif www_auth:
                self.headers['WWW-Authenticate'] = www_auth.to_header()
        header = self.headers.get('www-authenticate')
        return parse_www_authenticate_header(header, on_update)
1259392
def authenticate(self):
        """"""
        valid = self._session_check()
        if self._is_authenticated and valid:
            self._log.debug("[!] User has already authenticated")
            return
        init = self._session.get(url=self.LOGIN_URL, headers=self.HEADERS)
        soup = BeautifulSoup(init.content, "html.parser")
        soup_login = soup.find('form').find_all('input')
        post_data = dict()
        for u in soup_login:
            if u.has_attr('name') and u.has_attr('value'):
                post_data[u['name']] = u['value']
        post_data['Email'] = self._email
        post_data['Passwd'] = self._password
        response = self._session.post(url=self.AUTH_URL, data=post_data,
                                      headers=self.HEADERS)
        if self.CAPTCHA_KEY in str(response.content):
            raise AccountCaptcha('Google is forcing a CAPTCHA. To get around this issue, run the google-alerts with the seed option to open an interactive authentication session. Once authenticated, this module will cache your session and load that in the future')
        cookies = [x.name for x in response.cookies]
        if 'SIDCC' not in cookies:
            raise InvalidCredentials("Email or password was incorrect.")
        with open(SESSION_FILE, 'wb') as f:
            cookies = requests.utils.dict_from_cookiejar(self._session.cookies)
            pickle.dump(cookies, f, protocol=2)
            self._log.debug("Saved session to disk for future reference")
        self._log.debug("User successfully authenticated")
        self._is_authenticated = True
        self._process_state()
        return
604524
private boolean authenticate(byte method, InputStream in,
                                 BufferedOutputStream out) throws IOException {
        return authenticate(method, in, out, 0L);
    }