Get an access token from the "code" returned from an OAuth dialog.

        Returns a dict containing the user-specific access token and its
        expiration date (if applicable).
422202
def get_access_token_from_code(
        self, code, redirect_uri, app_id, app_secret
    ):
        
        args = {
            "code": code,
            "redirect_uri": redirect_uri,
            "client_id": app_id,
            "client_secret": app_secret,
        }

        return self.request(
            "{0}/oauth/access_token".format(self.version), args
        )
912372
function getAccessToken(authCode, callback) {
	debug('Getting access token');
	var responseJSON;
	if (refreshToken.length > 0) {
		request.post(psnURL.oauth, {form:{ // Refreshing the token with refresh_token to avoid login again
				 'grant_type'	: 'refresh_token'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'refresh_token': refreshToken
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						debug('access_token obtained by using refresh_token: ' + accessToken)
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + responseJSON)
					}
				}
				else {
					debug('ERROR: ' + error)
				}
		})
	}
	else {
		debug('Login for the first time');
		request.post(psnURL.oauth, {form:{ // Firts time login
				 'grant_type'	: 'authorization_code'
				,'client_id'	: psnVars.client_id
				,'client_secret': psnVars.client_secret
				,'code' 		: authCode
				,'redirect_uri'	: psnVars.redirectURL_oauth
				,'state' 		: 'x'
				,'scope'		: psnVars.scope_psn
				,'duid' 		: psnVars.duid
			}}, function (error, response, body) {
				responseJSON = JSON.parse(body);
				if (!error) {
					if ('access_token' in responseJSON && !('error' in responseJSON)) {
						accessToken = responseJSON.access_token;
						refreshToken = responseJSON.refresh_token;
						clearInterval(refreshInterval);
						refreshInterval = setInterval(function() {
							getAccessToken('', function() {
								debug('access_token refreshed after 59 minutes')
							})
						}, (responseJSON.expires_in - 60) * 1000) // 59 minutes
						debug('access_token/refresh_token obtained: ' + body);
						if (typeof callback === "function") callback();
					}
					else {
						debug('ERROR: ' + JSON.stringify(responseJSON))
					}
				}
				else {
					debug('ERROR: ' + JSON.stringify(error))
				}
		})	
	}
}
197716
def get_auth(self):
        
        if self.legacy_auth():
            return self._auth
        if not self.auth_expired():
            return self._auth
        self.claim_new_token()
        return self._auth
602756
def auth(self, code):
        
        request_data = self.get_access_token_params(code)

        res = self._session.post(**request_data)
        if res.status_code != 200:
            raise APIException(
                request_data['url'],
                res.status_code,
                response=res.content,
                request_param=request_data,
                response_header=res.headers
            )

        json_res = res.json()
        self.update_token(json_res)
        return json_res
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
98399
def retrieve_token(self):
        

        if self.authorization_code:
            request_param = {
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "redirect_uri": self.redirect_uri,
                "code": self.authorization_code
                }

            if self._extra_token_params:
                request_param.update(self._extra_token_params)

            content_length = len(urlencode(request_param))
            headers = {
                'Content-Length': str(content_length),
                'Content-Type': 'application/x-www-form-urlencoded'
                }
        
            r = requests.post(self.token_uri, data=request_param,
                              headers=headers)
            jsondata = json.loads(r.text)
            self.access_token = jsondata
            return self.access_token

        else:
            print("authorization code is required before getting accesss token")
            print("Please call retrieve_authorization_code() beforehand")
989567
def claim_exp(self, data):
        
        expiration = getattr(settings, 'OAUTH_ID_TOKEN_EXPIRATION', 30)
        expires = self.now + timedelta(seconds=expiration)
        return timegm(expires.utctimetuple())
522544
def _parse_access_token(self, r):
        '''
        
        '''
        current = int(time.time())
        expires = r.expires_in + current
        remind_in = r.get('remind_in', None)
        if remind_in:
            rtime = int(remind_in) + current
            if rtime < expires:
                expires = rtime
        return JsonDict(access_token=r.access_token, expires=expires, expires_in=expires, uid=r.get('uid', None))
1109037
def get_token_func():
        
        print("{}: token updater was triggered".format(datetime.datetime.now()))

        # in this example, the OAuth token is obtained using the ADAL library
        # however, the user can use any preferred method
        context = adal.AuthenticationContext(
            str.format("https://login.microsoftonline.com/{}", settings.ACTIVE_DIRECTORY_TENANT_ID),
            api_version=None, validate_authority=True)

        oauth_token = context.acquire_token_with_client_credentials(
            "https://storage.azure.com",
            settings.ACTIVE_DIRECTORY_APPLICATION_ID,
            settings.ACTIVE_DIRECTORY_APPLICATION_SECRET)

        # return the token itself and the interval to wait before this function should be called again
        # generally oauth_token['expiresIn'] - 180 is a good interval to give, as it tells the caller to
        # refresh the token 3 minutes before it expires, so here we are assuming that the token expiration
        # is at least longer than 3 minutes, the user should adjust it according to their AAD policy
        return oauth_token['accessToken'], oauth_token['expiresIn'] - 180
331570
public AccessToken getAccessToken(String code) {
        String url = WxEndpoint.get("url.oauth.accesstoken.get");
        String formatUrl = String.format(url, wxClient.getClientId(), wxClient.getClientSecret(), code);
        logger.debug("get access token: {}", formatUrl);
        String response = wxClient.get(formatUrl, false);
        return JsonMapper.defaultMapper().fromJson(response, AccessToken.class);
    }
478077
def get_last_codes(self, access_token=None, user_id=None):
        
        if access_token:
            self.req.credential.set_token(access_token)
        if user_id:
            self.req.credential.set_user_id(user_id)
        if not self.check_credentials():
            raise CredentialsError('credentials invalid')
        last = '/users/' + self.req.credential.get_user_id() + '/codes/lastest'
        return self.req.get(last, '&includeExecutions=true')['codes']
384536
def get_signed_in_token(self):
        
        response = self._send(http_method='GET',
                              location_id='6074ff18-aaad-4abb-a41e-5c75f6178057',
                              version='5.0-preview.1')
        return self._deserialize('AccessTokenResult', response)
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
154710
def get_access_token(self):
        
        if self.is_access_token_expired():

            if is_debug_enabled():
                debug('requesting new access_token')

            token = get_access_token(username=self.username,
                                     password=self.password,
                                     client_id=self.client_id,
                                     client_secret=self.client_secret,
                                     app_url=self.app_url)

            # lets make sure to refresh before we're halfway to expiring
            self.expires_at = time.time() + token['expires_in']/2
            self.access_token = token['access_token']

        return self.access_token
1235911
def _get_tokens(self, authn_response, context):
        
        if "code" in authn_response:
            # make token request
            args = {
                "code": authn_response["code"],
                "redirect_uri": self.client.registration_response['redirect_uris'][0],
            }

            token_resp = self.client.do_access_token_request(scope="openid", state=authn_response["state"],
                                                             request_args=args,
                                                             authn_method=self.client.registration_response[
                                                                 "token_endpoint_auth_method"])

            self._check_error_response(token_resp, context)
            return token_resp["access_token"], token_resp["id_token"]

        return authn_response.get("access_token"), authn_response.get("id_token")
674696
def get_access_token(self, code, state=None):
        '''
        
        '''
        kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
        if self._redirect_uri:
            kw['redirect_uri'] = self._redirect_uri
        if state:
            kw['state'] = state
        opener = build_opener(HTTPSHandler)
        request = Request('https://github.com/login/oauth/access_token', data=_encode_params(kw))
        request.get_method = _METHOD_MAP['POST']
        request.add_header('Accept', 'application/json')
        try:
            response = opener.open(request, timeout=TIMEOUT)
            r = _parse_json(response.read())
            if 'error' in r:
                raise ApiAuthError(str(r.error))
            return str(r.access_token)
        except HTTPError as e:
            raise ApiAuthError('HTTPError when get access token')
704867
def fetch_access_token(self, code):
        
        res = self._get(
            'sns/oauth2/component/access_token',
            params={
                'appid': self.app_id,
                'component_appid': self.component.component_appid,
                'component_access_token': self.component.access_token,
                'code': code,
                'grant_type': 'authorization_code',
            }
        )
        self.access_token = res['access_token']
        self.open_id = res['openid']
        self.refresh_token = res['refresh_token']
        self.expires_in = res['expires_in']
        self.scope = res['scope']
        return res