process an access_token request
returns the access token on success
353160
public function fetchAccessToken(&$request)
    {
        $this->getVersion($request);

        $consumer = $this->getConsumer($request);

        // requires authorized request token
        $token = $this->getToken($request, $consumer, "request");

        $this->checkSignature($request, $consumer, $token);

        // Rev A change
        $verifier = $request->get_parameter('oauth_verifier');
        $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);

        return $new_token;
    }
721205
def refresh_token(self, request, data, client):
        
        rt = self.get_refresh_token_grant(request, data, client)

        # this must be called first in case we need to purge expired tokens
        self.invalidate_refresh_token(rt)
        self.invalidate_access_token(rt.access_token)

        at = self.create_access_token(request, rt.user, rt.access_token.scope,
                client)
        rt = self.create_refresh_token(request, at.user, at.scope, at, client)

        return self.access_token_response(at)
869199
def process_request(self, req, resp):  # pylint: disable=unused-argument
        

        try:
            creds = self._get_creds(req)
            self.auth_creds(*creds)
        except (AuthRejected, AuthRequired, InvalidAuthSyntax) as exc:
            exc.headers = self._error_headers
            if not self.optional:
                abort(exc)
1060482
def extract_access_token(request):
    
    auth_header = request.META.get('HTTP_AUTHORIZATION', '')

    if re.compile('^[Bb]earer\s{1}.+$').match(auth_header):
        access_token = auth_header.split()[1]
    else:
        access_token = request.GET.get('access_token', '')

    return access_token
1179874
def get_access_token(self, request, callback=None):
        """"""
        callback = request.build_absolute_uri(callback or request.path)
        if not self.check_application_state(request):
            logger.error('Application state check failed.')
            return None
        if 'code' in request.GET:
            args = {
                'client_id': self.consumer_key,
                'redirect_uri': callback,
                'client_secret': self.consumer_secret,
                'code': request.GET['code'],
                'grant_type': 'authorization_code',
            }
        else:
            logger.error('No code returned by the provider')
            return None
        try:
            response = self.request('post', self.access_token_url, data=args)
            response.raise_for_status()
        except RequestException as e:
            logger.error('Unable to fetch access token: {0}'.format(e))
            return None
        else:
            return response.text
113057
async def _request(
            self,
            method: str,
            url: str,
            *,
            access_token: str = None,
            access_token_expiration: datetime = None,
            headers: dict = None,
            params: dict = None,
            json: dict = None,
            ssl: bool = True) -> dict:
        """"""
        if (access_token_expiration
                and datetime.now() >= access_token_expiration):
            raise TokenExpiredError('Long-lived access token has expired')

        if not headers:
            headers = {}
        headers.update({'Content-Type': 'application/json'})

        if not params:
            params = {}
        if access_token:
            params.update({'access_token': access_token})

        try:
            async with async_timeout.timeout(self.request_timeout):
                async with self._websession.request(
                        method, url, headers=headers, params=params, json=json,
                        ssl=ssl) as resp:
                    resp.raise_for_status()
                    data = await resp.json(content_type=None)
                    _raise_for_remote_status(url, data)
        except ClientError as err:
            raise RequestError(
                'Error requesting data from {0}: {1}'.format(url, err))
        except asyncio.TimeoutError:
            raise RequestError('Timeout during request: {0}'.format(url))

        return data
858069
def process_request(self, request):
        """"""

        # User has already been authed by alternate middleware
        if hasattr(request, "facebook") and request.facebook:
            return

        request.facebook = False

        if not self.is_valid_path(request):
            return

        if self.is_access_denied(request):
            return authorization_denied_view(request)

        request.facebook = Facebook()
        oauth_token = False

        # Is there a token cookie already present?
        if 'oauth_token' in request.COOKIES:
            try:
                # Check if the current token is already in DB
                oauth_token = OAuthToken.objects.get(token=request.COOKIES['oauth_token'])
            except OAuthToken.DoesNotExist:
                request.facebook = False
                return

        # Is there a code in the GET request?
        elif 'code' in request.GET:
            try:
                graph = GraphAPI()

                # Exchange code for an access_token
                response = graph.get('oauth/access_token',
                    client_id = FACEBOOK_APPLICATION_ID,
                    redirect_uri = get_post_authorization_redirect_url(request, canvas=False),
                    client_secret = FACEBOOK_APPLICATION_SECRET_KEY,
                    code = request.GET['code'],
                )
        
                components = parse_qs(response)
                
                # Save new OAuth-token in DB
                oauth_token, new_oauth_token = OAuthToken.objects.get_or_create(
                    token = components['access_token'][0],
                    issued_at = now(),
                    expires_at = now() + timedelta(seconds = int(components['expires'][0]))
                )

            except GraphAPI.OAuthError:
                pass
        
        # There isn't a valid access_token
        if not oauth_token or oauth_token.expired:
            request.facebook = False
            return
        
        # Is there a user already connected to the current token?
        try:
            user = oauth_token.user
            if not user.authorized:
                request.facebook = False
                return
            user.last_seen_at = now()
            user.save()
        except User.DoesNotExist:
            graph = GraphAPI(oauth_token.token)
            profile = graph.get('me')
            
            # Either the user already exists and its just a new token, or user and token both are new
            try:
                user = User.objects.get(facebook_id = profile.get('id'))
                if not user.authorized:
                    if new_oauth_token:
                        user.last_seen_at = now()
                        user.authorized = True
                    else:
                        request.facebook = False
                        return
            except User.DoesNotExist:
                # Create a new user to go with token
                user = User.objects.create(
                    facebook_id = profile.get('id'),
                    oauth_token = oauth_token
                )                    
            
            user.synchronize(profile)
            
            # Delete old access token if there is any and  only if the new one is different
            old_oauth_token = None
            if user.oauth_token != oauth_token:
                old_oauth_token = user.oauth_token
                user.oauth_token = oauth_token
            
            user.save()

            if old_oauth_token:
                old_oauth_token.delete()

        if not user.oauth_token.extended:
            # Attempt to extend the OAuth token, but ignore exceptions raised by
            # bug #102727766518358 in the Facebook Platform.
            #
            # http://developers.facebook.com/bugs/102727766518358/
            try:
                user.oauth_token.extend()
            except:
                pass

        request.facebook.user = user
        request.facebook.oauth_token = oauth_token
857126
def access_token_response(self, access_token):
        

        response_data = {
            'access_token': access_token.token,
            'token_type': constants.TOKEN_TYPE,
            'expires_in': access_token.get_expire_delta(),
            'scope': ' '.join(scope.names(access_token.scope)),
        }

        # Not all access_tokens are given a refresh_token
        # (for example, public clients doing password auth)
        try:
            rt = access_token.refresh_token
            response_data['refresh_token'] = rt.token
        except ObjectDoesNotExist:
            pass

        return HttpResponse(
            json.dumps(response_data), mimetype='application/json'
        )
549537
def _get_request_token(self):
        
        if self.request_token is None:
            get_params = {}
            if self.parameters:
                get_params.update(self.parameters)
            get_params['oauth_callback'] \
                = self.request.build_absolute_uri(self.callback_url)
            rt_url = self.request_token_url + '?' + urlencode(get_params)
            oauth = OAuth1(self.consumer_key,
                           client_secret=self.consumer_secret)
            response = requests.post(url=rt_url, auth=oauth)
            if response.status_code not in [200, 201]:
                raise OAuthError(
                    _('Invalid response while obtaining request token'
                      ' from "%s".') % get_token_prefix(
                          self.request_token_url))
            self.request_token = dict(parse_qsl(response.text))
            self.request.session['oauth_%s_request_token' % get_token_prefix(
                self.request_token_url)] = self.request_token
        return self.request_token
895039
function GetAccessToken(callback)
	{
		// do we have a refresh token? Or do we need to login from scratch?
		if (auth_obj.refresh_token)
		{
			// we have a refresh token!
			Log("Refreshing session...");

			if (!auth_obj.refresh_token)
			{
				if (callback) callback("No refresh token found!");
				return;
			}

			// request new access_token
			request.post(
				{
					url: urls.oauth,
					form: GetOAuthData({
						"grant_type": 		"refresh_token",
						"refresh_token": 	auth_obj.refresh_token
					})
				},
				function(err, response, body)
				{
					_ParseTokenResponse(err, body, callback);
				}
			);
		}
		else
		{
			// no refresh token, sign-in from scratch
			Log("Signing in with OAuth...");

			// make sure we have an authcode
			if (!auth_obj.auth_code)
			{
				if (callback) callback("No authcode available for OAuth!");
				return;
			}

			// request initial access_token
			request.post(
				{
					url: urls.oauth,
					form: GetOAuthData({
						"grant_type": 	"authorization_code",
						"code": 		auth_obj.auth_code
					})
				},
				function(err, response, body)
				{
					_ParseTokenResponse(err, body, callback);
				}
			);
		}
	}
416972
def _on_access_token(self, future, response):
        
        content = escape.json_decode(response.body)
        if 'error' in content:
            LOGGER.error('Error fetching access token: %s', content['error'])
            future.set_exception(auth.AuthError('Github auth error: %s' %
                                                str(content['error'])))
            return
        callback = self.async_callback(self._on_github_user, future,
                                       content['access_token'])
        self.github_request('user', callback, content['access_token'])
378790
def do_get(endpoint, access_token):
    '''
    '''
    headers = {"Authorization": 'Bearer ' + access_token}
    headers['User-Agent'] = get_user_agent()
    return requests.get(endpoint, headers=headers).json()
471510
def parse_access_token(self):
        
        access_file = os.path.join(self.file_path, 'access_token')
        # Ensure that the access_token file exists
        if os.path.isfile(access_file):
            # Initialise a list to store the secret and token
            access_list = list()
            with open(access_file, 'r') as access_token:
                for line in access_token:
                    value, data = line.split('=')
                    access_list.append(data.rstrip())
            # Set the variables appropriately
            self.access_secret = access_list[0]
            self.access_token = access_list[1]
        else:
            print('Missing access_token')
            self.get_request_token()
            self.get_access_token()
48553
def request(uri, data=nil, verb=:post)
      @logger.info(uri) if @logger
      auth_check
      query = {
        path: File.join('v1.0/me/', URI.escape(uri)),
        headers: {
          'Authorization': "Bearer #{@access_token.token}"
        }
      }
      if data
        query[:body] = JSON.generate(data)
        query[:headers]['Content-Type'] = 'application/json'
        @logger.info(query[:body]) if @logger
        verb = :post unless [:post, :put, :patch, :delete].include?(verb)
        response = @conn.send(verb, query)
      else
        response = @conn.get(query)
      end
      JSON.parse(response.body)
    end
1005862
def access_token(self):
        """"""
        access_token = self.get_auth_bearer()
        if not access_token:
            access_token = self.query_kwargs.get('access_token', '')
            if not access_token:
                access_token = self.body_kwargs.get('access_token', '')

        return access_token
515561
public function getAccessToken($query_data, $request_token) {

    $post = array(
      'client_id' => $this->getConfig('consumer_key'),
      'client_secret' => $this->getConfig('consumer_secret'),
      'redirect_uri' => $request_token['callback_uri'],
      'code' => $query_data['code'],
      'grant_type' => 'authorization_code',
    );
    //Get request token
    $response = $this->post($this->getConfig('access_token_path'), NULL, $post)->send();
    $access_token = array();
    parse_str($response->getBody(), $access_token);
    if (!isset($access_token['access_token'])) {
      // try to read json
      $access_token = $response->json();
    }
    $access_token['request_time'] = time();

    // Throw exception if there isn't a access token.
    if (!isset($access_token['access_token'])) {
      throw new \Exception('No access token found in response.');
    }

    if ($this->getConfig()->get('exchange_short_access_token')) {
      $access_token = $this->exchangeAccessToken($access_token);
    }

    // Return AccessToken
    return $this->normalizeAccessToken($access_token);
  }
917687
def callback_oauth1(self, request, **kwargs):
        
        if kwargs.get('access_token') == '' or kwargs.get('access_token') is None:
            access_token = self.get_access_token(request.session['oauth_token'],
                                                 request.session.get('oauth_token_secret', ''),
                                                 request.GET.get('oauth_verifier', ''))
        else:
            access_token = kwargs.get('access_token')

        if type(access_token) == str:
            token = access_token
        else:
            token = '#TH#'.join((access_token.get('oauth_token'), access_token.get('oauth_token_secret')))
        return token