Get an access token from an username and password combination.
        In order to get this working you need to create an app at
        http://twitter.com/apps, after that send a mail to api@twitter.com
        and request activation of xAuth for it.
553081
def get_xauth_access_token(self, username, password):
        
        try:
            url = self._get_oauth_url('access_token')
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            r = requests.post(url=url,
                              auth=oauth,
                              headers={'x_auth_mode': 'client_auth',
                                       'x_auth_username': username,
                                       'x_auth_password': password})

            credentials = parse_qs(r.content)
            return credentials.get('oauth_token')[0], credentials.get('oauth_token_secret')[0]
        except Exception as e:
            raise TweepError(e)
1303383
private User addUser(String userName)
    {
        User user = new User();
        PersonalDetail personalDetail = new PersonalDetail(userName, userName + "Password", "Single");
        user.setUserId(userName);
        user.setEmailId(userName + "@" + userName + ".com");
        user.setFirstName(userName);
        user.setLastName(userName);
        user.setTweets(new HashSet<Tweets>());
        user.setPersonalDetail(personalDetail);
        return user;
    }
1112401
def create_user(name,
                username,
                email,
                password,
                token_manager=None,
                app_url=defaults.APP_URL):
    
    headers = token_manager.get_access_token_headers()
    auth_url = environment.get_auth_url(app_url=app_url)
    url = "%s/api/v1/accounts" % auth_url

    payload = {
        'name': name,
        'username': username,
        'email': email,
        'password': password
    }

    response = requests.post(url,
                             data=json.dumps(payload),
                             headers=headers)

    if response.status_code == 201:
        return response.json()

    else:
        raise JutException('Error %s: %s' % (response.status_code, response.text))
324102
def login(self, username, password):
        '''
        '''
        response = self.request(
            ACCESS_TOKEN,
            {
                'x_auth_mode': 'client_auth',
                'x_auth_username': username,
                'x_auth_password': password
            },
            returns_json=False
        )
        token = dict(parse_qsl(response['data'].decode()))
        self.token = oauth.Token(
            token['oauth_token'], token['oauth_token_secret'])
        self.oauth_client = oauth.Client(self.consumer, self.token)
839450
def _login(self, username, password):
        """"""
        data = {
            'username': username,
            'password': password,
            'grant_type': 'password'
        }
        r = self.spark_api.oauth.token.POST(auth=('spark', 'spark'), data=data, timeout=self.timeout)
        self._check_error(r)
        return r.json()['access_token']
98311
def authenticate(cmd_args, endpoint='', force=False):
    
    server = server_url(cmd_args)
    network.check_ssl()
    access_token = None

    try:
        assert not force
        access_token = refresh_local_token(server)
    except Exception:
        print('Performing authentication')
        access_token = perform_oauth(get_code, cmd_args, endpoint)
        email = display_student_email(cmd_args, access_token)
        if not email:
            log.warning('Could not get login email. Try logging in again.')

    log.debug('Authenticated with access token={}'.format(access_token))

    return access_token
128933
def get_twitter(app_key=None, app_secret=None, search='python', location='', **kwargs):
    """"""
    if not app_key:
        from settings_secret import TWITTER_API_KEY as app_key
    if not app_secret:
        from settings_secret import TWITTER_API_SECRET as app_secret
    twitter = Twython(app_key, app_secret, oauth_version=2)
    return Twython(app_key, access_token=twitter.obtain_access_token())
775769
def pass_creds_to_nylas(name, email, password, server_host=None):
    
    # Start the connection process by looking up all the information that
    # Nylas needs in order to connect, and sending it to the authorize API.
    nylas_authorize_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "name": name,
        "email_address": email,
        "provider": "exchange",
        "settings": {"username": email, "password": password},
    }
    if server_host:
        nylas_authorize_data["settings"]["eas_server_host"] = server_host

    nylas_authorize_resp = requests.post(
        "https://api.nylas.com/connect/authorize", json=nylas_authorize_data
    )
    if not nylas_authorize_resp.ok:
        message = nylas_authorize_resp.json()["message"]
        raise APIError(message)

    nylas_code = nylas_authorize_resp.json()["code"]

    # Now that we've got the `code` from the authorize response,
    # pass it to the token response to complete the connection.
    nylas_token_data = {
        "client_id": app.config["NYLAS_OAUTH_CLIENT_ID"],
        "client_secret": app.config["NYLAS_OAUTH_CLIENT_SECRET"],
        "code": nylas_code,
    }
    nylas_token_resp = requests.post(
        "https://api.nylas.com/connect/token", json=nylas_token_data
    )
    if not nylas_token_resp.ok:
        message = nylas_token_resp.json()["message"]
        raise APIError(message)

    nylas_access_token = nylas_token_resp.json()["access_token"]

    # Great, we've connected the Exchange account to Nylas!
    # In the process, Nylas gave us an OAuth access token, which we'll need
    # in order to make API requests to Nylas in the future.
    # We'll save that access token in the Flask session, so we can pick it up
    # later and use it when we need it.
    session["nylas_access_token"] = nylas_access_token

    # We're all done here. Redirect the user back to the success page,
    # which will pick up the access token we just saved.
    return redirect(url_for("success"))
479509
def authenticate(self):
        '''
        
        '''
        if "username" in self.options and "password" in self.options:
            self.login_oauth2(
                self.options["username"],
                self.options["password"],
                self.options.get('mfa_code'))
        elif "access_token" in self.options:
            if "refresh_token" in self.options:
                self.access_token = self.options["access_token"]
                self.refresh_token = self.options["refresh_token"]
                self.__set_account_info()
        else:
            self.authenticated = False
        return self.authenticated
141358
function generateAuthMsg(params) {
    var message = {
        application_id: config.creds.appId,
        auth_key: config.creds.authKey,
        nonce: Utils.randomNonce(),
        timestamp: Utils.unixTime()
    };

    // With user authorization
    if (params.login && params.password) {
        message.user = {login: params.login, password: params.password};
    } else if (params.email && params.password) {
        message.user = {email: params.email, password: params.password};
    } else if (params.provider) {
        // Via social networking provider (e.g. facebook, twitter etc.)
        message.provider = params.provider;
        if (params.scope) {
            message.scope = params.scope;
        }
        if (params.keys && params.keys.token) {
            message.keys = {token: params.keys.token};
        }
        if (params.keys && params.keys.secret) {
            message.keys.secret = params.keys.secret;
        }
    }

    return message;
}
1058605
public function accessToken ()
	{
		OAuthRequestLogger::start($this);

		try
		{
			$this->verify('request');

			$options = array();
			$ttl     = $this->getParam('xoauth_token_ttl', false);
			if ($ttl)
			{
				$options['token_ttl'] = $ttl;
			}

			$verifier = $this->getParam('oauth_verifier', false);
 			if ($verifier) {
 				$options['verifier'] = $verifier;
 			}
			
			$store  = OAuthStore::instance();
			$token  = $store->exchangeConsumerRequestForAccessToken($this->getParam('oauth_token', true), $options);
			$result = 'oauth_token='.$this->urlencode($token['token'])
					.'&oauth_token_secret='.$this->urlencode($token['token_secret']);
					
			if (!empty($token['token_ttl']))
			{
				$result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']);
			}
					
			header('HTTP/1.1 200 OK');
			header('Content-Length: '.strlen($result));
			header('Content-Type: application/x-www-form-urlencoded');

			echo $result;
		}
		catch (OAuthException2 $e)
		{
			header('HTTP/1.1 401 Access Denied');
			header('Content-Type: text/plain');

			echo "OAuth Verification Failed: " . $e->getMessage();
		}
		
		OAuthRequestLogger::flush();
		exit();
	}
890791
def redirect_to_twitter_auth_url
      request_token = get_request_token
    
      session[:request_token] = request_token.token
      session[:request_token_secret]= request_token.secret
    
      redirect request_token.authorize_url.gsub('authorize','authenticate')
    end
1269569
def get_security_token!(parameters = {})
      username = parameters[:username] || @options.username
      password = parameters[:password] || @options.password
      appname = parameters[:appname] || @options.appname

      request_data = {
        'Username' => username,
        'Password' => password,
        'Appname' => appname
      }

      start_timer
      response = @connection.post(build_uri('GetToken'), MultiJson.dump(request_data.to_hash))
      end_timer

      log_get_security_token
      log_info("Response Status: #{response.status}")

      if response.status != 200
        raise make_get_security_token_error
      else
        raise_if_response_error(response)

        @security_token = response.body
      end
    end
1330619
def setup_oauth(username, password, basemaps_token_uri, authcfg_id=AUTHCFG_ID, authcfg_name=AUTHCFG_NAME):
    
    cfgjson = {
     "accessMethod" : 0,
     "apiKey" : "",
     "clientId" : "",
     "clientSecret" : "",
     "configType" : 1,
     "grantFlow" : 2,
     "password" : password,
     "persistToken" : False,
     "redirectPort" : '7070',
     "redirectUrl" : "",
     "refreshTokenUrl" : "",
     "requestTimeout" : '30',
     "requestUrl" : "",
     "scope" : "",
     "state" : "",
     "tokenUrl" : basemaps_token_uri,
     "username" : username,
     "version" : 1
    }

    if authcfg_id not in auth_manager().availableAuthMethodConfigs():
        authConfig = QgsAuthMethodConfig('OAuth2')
        authConfig.setId(authcfg_id)
        authConfig.setName(authcfg_name)
        authConfig.setConfig('oauth2config', json.dumps(cfgjson))
        if auth_manager().storeAuthenticationConfig(authConfig):
            return authcfg_id
    else:
        authConfig = QgsAuthMethodConfig()
        auth_manager().loadAuthenticationConfig(authcfg_id, authConfig, True)
        authConfig.setName(authcfg_name)
        authConfig.setConfig('oauth2config', json.dumps(cfgjson))
        if auth_manager().updateAuthenticationConfig(authConfig):
            return authcfg_id
    return None
459723
def _obtain_api_token(self, username, password):
        """"""
        data = self._request("POST", "auth/apitoken",
                             {"username": username, "password": password},
                             reestablish_session=False)
        return data["api_token"]
1306992
def get_token(self, appname, username, password):
        
        ext_exception = TouchWorksException(
            TouchWorksErrorMessages.GET_TOKEN_FAILED_ERROR)
        data = {'Username': username,
                'Password': password}
        resp = self._http_request(TouchWorksEndPoints.GET_TOKEN, data)
        try:
            logger.debug('token : %s' % resp)
            if not resp.text:
                raise ext_exception
            try:
                uuid.UUID(resp.text, version=4)
                return SecurityToken(resp.text)
            except ValueError:
                logger.error('response was not valid uuid string. %s' % resp.text)
                raise ext_exception

        except Exception as ex:
            logger.exception(ex)
            raise ext_exception
1138547
def get_token(username, password, server):
    
    method = 'PUT'
    uri = 'https://' + server + '/authenticate'
    token = ''

    authinfo = {
        "username": username,
        "password": password,
        "local_user": username}

    token = tonicdns_client(uri, method, token, data=authinfo)

    return token