Take the oauth2 request token and turn it into an access token
 which can be used to access private data
974107
def authorize(callback_url, code)
      data = open("#{BASE_URL}/oauth/access_token?client_id=#{app_id}&redirect_uri=#{CGI.escape callback_url}&client_secret=#{app_secret}&code=#{CGI.escape code}").read
      
      # The expiration date is not necessarily set, as the app might have
      # requested offline_access to the data
      match_data = data.match(/expires=([^&]+)/)
      @expires = match_data && match_data[1] || nil
      
      # Extract the access token
      @access_token = data.match(/access_token=([^&]+)/)[1]
    end
433140
def finalize_oauth(self, access_token, access_token_secret):
        
        self.access_token = access_token
        self.access_token_secret = access_token_secret

        # Final OAuth object
        self.oauth = OAuth1(
            self.consumer_key,
            client_secret=self.consumer_secret,
            resource_owner_key=self.access_token,
            resource_owner_secret=self.access_token_secret)
406059
def _get_access_token(self, code, **params):
        
        params.update({
            'code': code,
            'client_id': self.client_id,
            'client_secret': self.secret,
            'redirect_uri': self.get_callback_url(),
        })

        logger.debug("Params: %s", params)

        resp, content = self.request_access_token(params=params)

        content = smart_unicode(content)

        logger.debug("Status: %s", resp['status'])
        logger.debug("Content: %s", content)
        
        content = self.parse_access_token(content)
        
        if 'error' in content:
            raise OAuthError(_(
                u"Received error while obtaining access token from %s: %s") % (
                    self.access_token_url, content['error']))

        return content
730805
def fetch_access_token(self, oauth_request):
        
        version = self._get_version(oauth_request)
        consumer = self._get_consumer(oauth_request)
        try:
            verifier = self._get_verifier(oauth_request)
        except Error:
            verifier = None
        # Get the request token.
        token = self._get_token(oauth_request, 'request')
        self._check_signature(oauth_request, consumer, token)
        new_token = self.data_store.fetch_access_token(consumer, token, verifier)
        return new_token
793888
function getAccessToken(callback){

    console.log("Requesting access token from server...");

    var credentials = {
            scope: "messaging:push",
            grant_type: "client_credentials",
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET
    }

    var post_data = querystring.stringify(credentials);

    var post_options = {
      host: "api.amazon.com",
      port: "443",
      path: "/auth/O2/token",
      method: "POST",
      headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
      }
    };

    var req = https.request(post_options, function(res) {

        var data = "";

        res.on("data", function (chunk) {
            data += chunk;
        });

        res.on("end", function() {
            console.log("\nAccess token response:", data);
            var accessToken = JSON.parse(data).access_token;
            callback(accessToken);
        });

    });

    req.on("error", function(e) {
      console.log("\nProblem with access token request: ", e.message);
    });

    req.write(post_data);
    req.end();

}
346965
def _get_access_token(self, verifier=None):
        
        
        response, content = self.client(verifier).request(
            self.access_token_url, "POST")
        
        content = smart_unicode(content)

        if not response['status'] == '200':
            raise OAuthError(_(
                u"Invalid status code %s while obtaining access token from %s: %s") % 
                (response['status'], self.access_token_url, content))
        
        token = dict(urlparse.parse_qsl(content))
        
        
        return (oauth.Token(token['oauth_token'], token['oauth_token_secret']),
            token)
1350996
def _create_access_token(self, subject_identifier, auth_req, granted_scope, current_scope=None):
        # type: (str, Mapping[str, Union[str, List[str]]], str, Optional[str]) -> se_leg_op.access_token.AccessToken
        
        access_token = AccessToken(rand_str(), self.access_token_lifetime)

        scope = current_scope or granted_scope
        logger.debug('creating access token for scope=%s', scope)

        authz_info = {
            'iat': int(time.time()),
            'exp': int(time.time()) + self.access_token_lifetime,
            'sub': subject_identifier,
            'client_id': auth_req['client_id'],
            'aud': [auth_req['client_id']],
            'scope': scope,
            'granted_scope': granted_scope,
            'token_type': access_token.BEARER_TOKEN_TYPE,
            self.KEY_AUTHORIZATION_REQUEST: auth_req
        }
        self.access_tokens[access_token.value] = authz_info

        logger.debug('new access_token=%s to client_id=%s for sub=%s valid_until=%s',
                     access_token.value, auth_req['client_id'], subject_identifier, authz_info['exp'])
        return access_token
686469
def get_access_token(client_id, client_secret):
	'''
	
	'''

	headers = {'Content-Type': 'application/x-www-form-urlencoded'}
	payload = {
		'client_id': client_id,
		'client_secret': client_secret
	}

	request = requests.post(token_url, data=payload, headers=headers)
	if request.status_code == 200:
		token = request.json()
		return token

	return {'status': request.status_code, "message": request.text}
884472
def request_access_token(self, params):
        
        return self.client().request(self.access_token_url, method="POST", body=urllib.urlencode(params), headers={'Content-Type':'application/x-www-form-urlencoded'})
1312070
def build_access_token(response, access_token_opts, access_token_class)
      access_token_class.from_hash(self, response.parsed.merge(access_token_opts)).tap do |access_token|
        access_token.response = response if access_token.respond_to?(:response=)
      end
    end
1283586
def authorization_code(self, request, data, client):
        
        grant = self.get_authorization_code_grant(request, request.POST,
                client)
        if constants.SINGLE_ACCESS_TOKEN:
            at = self.get_access_token(request, grant.user, grant.scope, client)
        else:
            at = self.create_access_token(request, grant.user, grant.scope, client)
            rt = self.create_refresh_token(request, grant.user, grant.scope, at,
                    client)

        self.invalidate_grant(grant)

        return self.access_token_response(at)
329633
def request(self, method, url, **kwargs):
        ""
        user_token = kwargs.pop('token', self.token)
        token, secret = self.parse_raw_token(user_token)
        callback = kwargs.pop('oauth_callback', None)
        verifier = kwargs.get('data', {}).pop('oauth_verifier', None)
        oauth = OAuth1(
            resource_owner_key=token,
            resource_owner_secret=secret,
            client_key=self.provider.consumer_key,
            client_secret=self.provider.consumer_secret,
            verifier=verifier,
            callback_uri=callback,
        )
        kwargs['auth'] = oauth
        return super(OAuthClient, self).request(method, url, **kwargs)
450349
def create_token(credential, opts = {})
      data, _status_code, _headers = create_token_with_http_info(credential, opts)
      return data
    end
212855
def get_oauth_request(self):
        """"""

        try:
            method = os.environ['REQUEST_METHOD']
        except:
            method = 'GET'

        postdata = None
        if method in ('POST', 'PUT'):
            postdata = self.request.body

        return oauth.Request.from_request(method, self.request.uri,
            headers=self.request.headers, query_string=postdata)
1068322
def request_token(self):
        
        client = OAuth1(
            client_key=self._server_cache[self.client.server].key,
            client_secret=self._server_cache[self.client.server].secret,
            callback_uri=self.callback,
        )

        request = {"auth": client}
        response = self._requester(
            requests.post,
            "oauth/request_token",
            **request
        )

        data = parse.parse_qs(response.text)
        data = {
            'token': data[self.PARAM_TOKEN][0],
            'token_secret': data[self.PARAM_TOKEN_SECRET][0]
        }

        return data
1195177
def _request(self, base_url, client_id, client_secret,
                 parameters, **kwargs):
        """"""
        logging.debug('Getting an OAuth token for client "%s" with scope "%s"',
                      client_id, parameters.get('scope'))
        headers = {'Content-Type': 'application/x-www-form-urlencoded',
                   'Accept': 'application/json'}

        api = API(base_url,
                  auth_username=client_id,
                  auth_password=client_secret,
                  **kwargs)
        endpoint = api.auth.token

        response = yield endpoint.post(body=urllib.urlencode(parameters),
                                       request_timeout=60,
                                       headers=headers)

        logging.debug('Received token: %s', response.get('access_token'))
        raise Return(response)
325687
async def generate_access_token(self, user):
        
        payload = await self._get_payload(user)
        secret = self._get_secret(True)
        algorithm = self._get_algorithm()

        return jwt.encode(payload, secret, algorithm=algorithm).decode("utf-8")