Finish an OAuth session, converting the request to access tokens.
508474
public function confirmSession($token, $verifier)
    {
        if ($this->authentication->getTokenStorage()->getRequestToken() != $token) {
            throw new LogicException('The request tokens do not match.');
        }

        $response = $this->sendCustomOauthPostRequest(
            $this->config['access_url'],
            [
                'verifier' => $verifier,
                'token' => $this->authentication->getTokenStorage()->getRequestToken(),
                'token_secret' => $this->authentication->getTokenStorage()->getRequestTokenSecret(),
            ]
        );

        if (200 == $response->getStatusCode()) {
            parse_str($response->getBody(), $responseData);

            if (!isset($responseData['oauth_token'])) {
                throw new UnexpectedValueException('Oauth exchange is missing `oauth_token`.');
            } elseif (!isset($responseData['oauth_token_secret'])) {
                throw new UnexpectedValueException('Oauth exchange is missing `oauth_token_secret`.');
            }

            $this->authentication->getTokenStorage()->setAccessToken($responseData['oauth_token']);
            $this->authentication->getTokenStorage()->setAccessTokenSecret($responseData['oauth_token_secret']);
            $this->authentication->getTokenStorage()->setRequestToken(null);
            $this->authentication->getTokenStorage()->setRequestTokenSecret(null);

            $this->authentication->getTokenStorage()->save();

            // next time we should reload tokens
            $this->authentication->resetOauth();
        } else {
            throw new RuntimeException('Bad response');
        }
    }
473879
def _process_oauth_response(self, response):
        ""
        if response.status_code == 200:
            credentials = parse_qs(response.text)

            # Initialize the oauth credentials
            self._init_oauth(
                credentials.get('oauth_token')[0],
                credentials.get('oauth_token_secret')[0]
            )

            # If tokens are refreshable, we'll get a session handle
            self.oauth_session_handle = credentials.get(
                    'oauth_session_handle', [None])[0]

            # Calculate token/auth expiry
            oauth_expires_in = credentials.get(
                    'oauth_expires_in',
                    [OAUTH_EXPIRY_SECONDS])[0]
            oauth_authorisation_expires_in = credentials.get(
                    'oauth_authorization_expires_in',
                    [OAUTH_EXPIRY_SECONDS])[0]

            self.oauth_expires_at = datetime.datetime.now() + \
                                    datetime.timedelta(seconds=int(
                                        oauth_expires_in))
            self.oauth_authorization_expires_at = \
                                    datetime.datetime.now() + \
                                    datetime.timedelta(seconds=int(
                                        oauth_authorisation_expires_in))
        else:
            self._handle_error_response(response)
739289
def _get_at_from_session(self):
        
        try:
            return self.request.session['oauth_%s_access_token'
                                        % get_token_prefix(
                                            self.request_token_url)]
        except KeyError:
            raise OAuthError(
                _('No access token saved for "%s".')
                % get_token_prefix(self.request_token_url))
1206690
def cleanup_request(request):
        
        for method_type in ('GET', 'PUT', 'POST', 'DELETE'):
            block = getattr(request, method_type, { })

            if True in [ k.startswith("oauth_") for k in block.keys() ]:
                sanitized = block.copy()

                for k in sanitized.keys():
                    if k.startswith("oauth_"):
                        sanitized.pop(k)

                setattr(request, method_type, sanitized)

        return request
1100169
def process_request(self, request=None, cookie=None, **kwargs):
        
        _cntx = self.endpoint_context
        _sdb = _cntx.sdb

        if 'post_logout_redirect_uri' in request:
            if 'id_token_hint' not in request:
                raise InvalidRequest(
                    "If post_logout_redirect_uri then id_token_hint is a MUST")
        _cookie_name = self.endpoint_context.cookie_name['session']
        try:
            part = self.endpoint_context.cookie_dealer.get_cookie_value(
                cookie, cookie_name=_cookie_name)
        except IndexError:
            raise InvalidRequest('Cookie error')
        except KeyError:
            part = None

        if part:
            # value is a base64 encoded JSON document
            _cookie_info = json.loads(as_unicode(b64d(as_bytes(part[0]))))
            logger.debug('Cookie info: {}'.format(_cookie_info))
            _sid = _cookie_info['sid']
        else:
            logger.debug('No relevant cookie')
            _sid = ''
            _cookie_info = {}

        if 'id_token_hint' in request:
            logger.debug(
                'ID token hint: {}'.format(
                    request[verified_claim_name("id_token_hint")]))

            auds = request[verified_claim_name("id_token_hint")]['aud']
            _ith_sid = ''
            _sids = _sdb.sso_db.get_sids_by_sub(
                request[verified_claim_name("id_token_hint")]['sub'])

            if _sids is None:
                raise ValueError('Unknown subject identifier')

            for _isid in _sids:
                if _sdb[_isid]['authn_req']['client_id'] in auds:
                    _ith_sid = _isid
                    break

            if not _ith_sid:
                raise ValueError('Unknown subject')

            if _sid:
                if _ith_sid != _sid:  # someone's messing with me
                    raise ValueError('Wrong ID Token hint')
            else:
                _sid = _ith_sid
        else:
            auds = []

        try:
            session = _sdb[_sid]
        except KeyError:
            raise ValueError("Can't find any corresponding session")

        client_id = session['authn_req']['client_id']
        # Does this match what's in the cookie ?
        if _cookie_info:
            if client_id != _cookie_info['client_id']:
                logger.warning(
                    'Client ID in authz request and in cookie does not match')
                raise ValueError("Wrong Client")

        if auds:
            if client_id not in auds:
                raise ValueError('Incorrect ID Token hint')

        _cinfo = _cntx.cdb[client_id]

        # verify that the post_logout_redirect_uri if present are among the ones
        # registered

        try:
            _uri = request['post_logout_redirect_uri']
        except KeyError:
            if _cntx.issuer.endswith('/'):
                _uri = "{}{}".format(_cntx.issuer,
                                     self.kwargs['post_logout_uri_path'])
            else:
                _uri = "{}/{}".format(_cntx.issuer,
                                      self.kwargs['post_logout_uri_path'])
            plur = False
        else:
            plur = True
            verify_uri(_cntx, request, 'post_logout_redirect_uri',
                       client_id=client_id)

        payload = {
            'sid': _sid, 'client_id': client_id,
            'user': session['authn_event']['uid']
        }

        # redirect user to OP logout verification page
        if plur and 'state' in request:
            _uri = '{}?{}'.format(_uri, urlencode({'state': request['state']}))
            payload['state'] = request['state']

        payload['redirect_uri'] = _uri

        logger.debug('JWS payload: {}'.format(payload))
        # From me to me
        _jws = JWT(_cntx.keyjar, iss=_cntx.issuer, lifetime=86400,
                   sign_alg=self.kwargs['signing_alg'])
        sjwt = _jws.pack(payload=payload, recv=_cntx.issuer)

        location = '{}?{}'.format(self.kwargs['logout_verify_url'],
                                  urlencode({'sjwt': sjwt}))
        return {'redirect_location': location}
324398
def prepare(self):
        
        requested_access = self.endpoint_access(self.request.method)
        use_oauth = getattr(options, 'use_oauth', None)
        if use_oauth and requested_access is not self.UNAUTHENTICATED_ACCESS:
            token = self.request.headers.get('Authorization', '').split(' ')[-1]
            if token:
                has_access = yield self.verify_token(token, requested_access)
                if not has_access:
                    msg = "'{}' access not granted.".format(requested_access)
                    raise HTTPError(403, msg)
            else:
                msg = 'OAuth token not provided'
                raise HTTPError(401, msg)
255778
def r_oauth_logout(self):
        
        session.pop('oauth_user_uri', None)
        session.pop('oauth_user_name', None)
        next = request.args.get('next','')
        if next is not None:
            return redirect(session['next'])
        else:
            return {
                "template": "main::index.html"
            }
454656
def on_finish(self):
        
        super(SessionRequestHandler, self).on_finish()
        LOGGER.debug('Entering SessionRequestHandler.on_finish: %s',
                     self.session.id)
        self.session.last_request_at = self.current_epoch()
        self.session.last_request_uri = self.request.uri
        if self.session.dirty:
            result = yield self.session.save()
            LOGGER.debug('on_finish yield save: %r', result)
        self.session = None
        LOGGER.debug('Exiting SessionRequestHandler.on_finish: %r',
                     self.session)
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)
615424
def _request(self, method, resource, **kwargs):
        
        url = self._resolve_resource_name(resource)

        if hasattr(self, 'access_token'):
            kwargs.update(dict(oauth_token=self.access_token))
        if hasattr(self, 'client_id'):
            kwargs.update(dict(client_id=self.client_id))

        kwargs.update({
            'verify_ssl': self.options.get('verify_ssl', True),
            'proxies': self.options.get('proxies', None)
        })
        return wrapped_resource(make_request(method, url, kwargs))
587481
def request(self, method, url, **kwargs):
        ""
        user_token = kwargs.pop('token', self.token)
        token, _ = self.parse_raw_token(user_token)
        if token is not None:
            params = kwargs.get('params', {})
            params['access_token'] = token
            kwargs['params'] = params
        return super(OAuth2Client, self).request(method, url, **kwargs)
1066753
def auth_complete(self, *args, **kwargs):
        """"""
        if SESSION_VAR not in self.strategy.request.session:
            # This is the only protection layer when people
            # go directly to the passthrough login view.
            logger.warn("Auth data for passthrough provider not found in session. Raising 404.")
            raise PermissionDenied
        auth_data = self.strategy.request.session[SESSION_VAR]
        kwargs.update({'response': auth_data, 'backend': self})
        return self.strategy.authenticate(*args, **kwargs)
877068
def create_request_token(self, request, credentials):
        
        token = {
            'oauth_token': self.token_generator(),
            'oauth_token_secret': self.token_generator(),
            'oauth_callback_confirmed': 'true'
        }
        token.update(credentials)
        self.request_validator.save_request_token(token, request)
        return urlencode(token.items())
111275
def _do_request(self, method, endpoint, data=None):
        
        # No token - authorize
        if self.token is None:
            self._do_authorize()

        r = requests.request(
            method,
            "{0}{1}".format(self.base_url, endpoint),
            headers={
                "Authorization": "Bearer {0}".format(self.token),
                "Content-Type": "application/json"
            },
            json=data,
            verify=self.verify_certificate,
            timeout=self.timeout
        )

        if r.status_code == 401:
            self._do_authorize()
            r = requests.request(
                method,
                "{0}{1}".format(self.base_url, endpoint),
                headers={
                    "Authorization": "Bearer {0}".format(self.token),
                    "Content-Type": "application/json"
                },
                json=data,
                verify=self.verify_certificate,
                timeout=self.timeout
            )

        return r
342971
function refreshToken($accessToken, $sessionHandle) {
		$code = $this->request ( 'GET', $this->url ( 'AccessToken', '' ), array (
				'oauth_token' => $accessToken,
				'oauth_session_handle' => $sessionHandle 
		) );
		if ($this->response ['code'] == 200) {
			
			$response = $this->extract_params ( $this->response ['response'] );
			
			return $response;
		} else {
			$this->response ['helper'] = "TokenFatal";
			return $this->response;
		}
	}
439171
def get_access_token(self, request, callback=None):
        ""
        raw_token = request.session.get(self.session_key, None)
        verifier = request.GET.get('oauth_verifier', None)
        if raw_token is not None and verifier is not None:
            data = {'oauth_verifier': verifier}
            callback = request.build_absolute_uri(callback or request.path)
            callback = force_text(callback)
            try:
                response = self.request('post', self.provider.access_token_url,
                                        token=raw_token, data=data, oauth_callback=callback)
                response.raise_for_status()
            except RequestException as e:
                logger.error('Unable to fetch access token: {0}'.format(e))
                return None
            else:
                return response.text
        return None
203185
public void finish() {
        if (mAccountAuthenticatorResponse != null) {
            // send the result bundle back if set, otherwise send an error.
            if (mResultBundle != null) {
                mAccountAuthenticatorResponse.onResult(mResultBundle);
            } else {
                mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
                        "canceled");
            }
            mAccountAuthenticatorResponse = null;
        }
        super.finish();
    }