Authenticate against the API.
976720
async def authenticate(self, username: str, password: str) -> None:
        """"""
        self._credentials = {
            'username': username,
            'password': password,
        }

        await self._get_security_token()
1253446
def authenticate(self):
        
        if request.headers.get('Authorization') or request.args.get('access_token'):
            realm = 'Bearer realm="%s", error="invalid_token"' % __package__
        else:
            realm = 'Bearer realm="%s"' % __package__
        resp = Response(None, 401, {'WWW-Authenticate': realm})
        abort(401, description='Please provide proper credentials', response=resp)
202794
def authenticate(self):
        """"""

        # Temporarily remove auth from Swimlane session for auth request to avoid recursive loop during login request
        self._swimlane._session.auth = None
        resp = self._swimlane.request(
            'post',
            'user/login',
            json={
                'userName': self._username,
                'password': self._password
            },
        )
        self._swimlane._session.auth = self

        # Get JWT from response content
        json_content = resp.json()
        token = json_content.pop('token', None)

        # Grab token expiration
        token_data = jwt.decode(token, verify=False)
        token_expiration = pendulum.from_timestamp(token_data['exp'])

        headers = {
            'Authorization': 'Bearer {}'.format(token)
        }

        # Create User instance for authenticating user from login response data
        user = User(self._swimlane, _user_raw_from_login_content(json_content))

        self._login_headers = headers
        self.user = user
        self._token_expiration = token_expiration
195364
def _verify_authentication(self, handler, args, kwargs):
        
        if not self.user_manager.session_logged_in():
            raise APIForbidden()
        return handler(*args, **kwargs)
325812
def authenticated(function):
    """"""
    def wrapped(*args):
        """Wrap function."""
        try:
            return function(*args)
        except FedexError:
            _login(*args)
            return function(*args)
    return wrapped
1130411
def authenticate(self, request):
        
        authenticators = self._meta.authenticators

        if request.method == 'OPTIONS' and ADREST_ALLOW_OPTIONS:
            self.auth = AnonimousAuthenticator(self)
            return True

        error_message = "Authorization required."
        for authenticator in authenticators:
            auth = authenticator(self)
            try:
                if not auth.authenticate(request):
                    raise AssertionError(error_message)

                self.auth = auth
                auth.configure(request)
                return True
            except AssertionError, e:
                error_message = str(e)

        raise HttpError(error_message, status=status.HTTP_401_UNAUTHORIZED)
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());
        }
    }
377460
def authenticate(self):
        """"""
        postdata = self.authentication_postdata
        jar = requests.cookies.cookielib.CookieJar()
        self.cookies = jar
        resp = self.get(self.authentication_base_url)
        authtok = _extract_authenticity_token(resp.content)
        if postdata is None:
            # This works for GitHub
            postdata = {"login": self.oauth2_username,
                        "password": self._oauth2_password,
                        "authenticity_token": authtok,
                        "commit": "Sign+in",
                        "utf8": u"\u2713",
                        }  # pylint: disable=bad-continuation
            self.authentication_postdata = postdata
        if self.authentication_session_url is None:
            # This is also for GitHub
            authentication_session_url = "https://github.com/session"
            self.authentication_session_url = authentication_session_url
        self.post(self.authentication_session_url, data=postdata)
837237
def authenticate(self, username, password):
        

        r = self._query_('/users/authenticate', 'POST',
                         params={'username': username,
                                 'password': password})
        if r.status_code == 201:
            return r.text.strip('"')
        else:
            raise ValueError('Authentication invalid.')
968936
public static TrainingApi authenticate(RestClient restClient, final String apiKey) {
        return new TrainingApiImpl(restClient).withApiKey(apiKey);
    }
201713
def auth(context, request):
    

    if ploneapi.user.is_anonymous():
        request.response.setStatus(401)
        request.response.setHeader('WWW-Authenticate',
                                   'basic realm="JSONAPI AUTH"', 1)

    logger.info("*** BASIC AUTHENTICATE ***")
    return {}
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);
        }
    }
601182
def authenticate_credentials(self, payload):
        """"""
        username = payload.get('preferred_username') or payload.get('username')

        if username is None:
            raise exceptions.AuthenticationFailed('JWT must include a preferred_username or username claim!')
        else:
            try:
                user, __ = get_user_model().objects.get_or_create(username=username)
                attributes_updated = False
                for claim, attr in self.get_jwt_claim_attribute_map().items():
                    payload_value = payload.get(claim)

                    if getattr(user, attr) != payload_value and payload_value is not None:
                        setattr(user, attr, payload_value)
                        attributes_updated = True

                if attributes_updated:
                    user.save()
            except:
                msg = 'User retrieval failed.'
                logger.exception(msg)
                raise exceptions.AuthenticationFailed(msg)

        return user
927156
def authenticate_eauth(self, load):
        '''
        
        '''
        if 'eauth' not in load:
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        if load['eauth'] not in self.opts['external_auth']:
            log.warning('The eauth system "%s" is not enabled', load['eauth'])
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        # Perform the actual authentication. If we fail here, do not
        # continue.
        if not self.time_auth(load):
            log.warning('Authentication failure of type "eauth" occurred.')
            return False

        return True
512960
def authenticate(self):
        
        if self._auth_token is None or self._token_expiry < time.time():
            self._perform_auth()

        yield self._auth_token
850253
def authenticate(self):
        """"""
        if self.__token:
            try:
                resp = self._refresh_token()
            except exceptions.TVDBRequestException as err:
                # if a 401 is the cause try to login
                if getattr(err.response, 'status_code', 0) == 401:
                    resp = self._login()
                else:
                    raise
        else:
            resp = self._login()

        self.__token = resp.get('token')
        self._token_timer = timeutil.utcnow()
1099270
def authenticate(self, request):
        
        auth = get_authorization_header(request).split()

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

        if len(auth) == 1:
            msg = _('Invalid basic header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid basic header. Credentials string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            auth_parts = base64.b64decode(auth[1]).decode(HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError):
            msg = _('Invalid basic header. Credentials not correctly base64 encoded.')
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        return self.authenticate_credentials(userid, password)