Session token operations
488208
public Observable<Boolean> checkAuthenticatedInBackground() {
    String sessionToken = getSessionToken();
    if (StringUtil.isEmpty(sessionToken)) {
      logger.d("sessionToken is not existed.");
      return Observable.just(false);
    }
    return PaasClient.getStorageClient().checkAuthenticated(sessionToken);
  }
13656
protected function setSessionToken()
    {
        $token = $this->session->get('twitter.oauth_token');
        $tokenSecret = $this->session->get('twitter.oauth_token_secret');

        $this->setToken($token, $tokenSecret);
    }
1137261
def parse_session_token(self):
        
        session_file = os.path.join(self.file_path, 'session_token')
        # Only try to extract the strings if the file exists
        if os.path.isfile(session_file):
            # Create a list to store the data from the file
            session_list = list()
            with open(session_file, 'r') as session_token:
                for line in session_token:
                    # Split the description e.g. secret= from the line
                    value, data = line.split('=')
                    # Add each string to the list
                    session_list.append(data.rstrip())
            # Extract the appropriate variable from the list
            self.session_secret = session_list[0]
            self.session_token = session_list[1]
948128
def Call(method,url,payload=None,session=None,debug=False):
		
		if session is not None:
			token = session['token']
			http_session = session['http_session']

		else:
			if not clc._LOGIN_TOKEN_V2:
				API._Login()
			token = clc._LOGIN_TOKEN_V2
			http_session = clc._REQUESTS_SESSION

		if payload is None:
		    payload = {}

		# If executing refs provided in API they are abs paths,
		# Else refs we build in the sdk are relative
		if url[0]=='/':  fq_url = "%s%s" % (clc.defaults.ENDPOINT_URL_V2,url)
		else:  fq_url = "%s/v2/%s" % (clc.defaults.ENDPOINT_URL_V2,url)

		http_session.headers.update({'Authorization': "Bearer %s" % token})

		if isinstance(payload, basestring):  http_session.headers['content-type'] = "Application/json" # added for server ops with str payload
		else:  http_session.headers['content-type'] = "application/x-www-form-urlencoded"

		if method=="GET":
			r = http_session.request(method,fq_url,
			                     params=payload,
								 verify=API._ResourcePath('clc/cacert.pem'))
		else:
			r = http_session.request(method,fq_url,
			                     data=payload,
								 verify=API._ResourcePath('clc/cacert.pem'))

		if debug:
			API._DebugRequest(request=requests.Request(method,fq_url,data=payload,headers=http_session.headers).prepare(),
			                  response=r)

		if r.status_code>=200 and r.status_code<300:
			try:
				return(r.json())
			except:
				return({})
		else:
			try:
				e = clc.APIFailedResponse("Response code %s.  %s %s %s" %
				                          (r.status_code,r.json()['message'],method,fq_url))
				e.response_status_code = r.status_code
				e.response_json = r.json()
				e.response_text = r.text
				raise(e)
			except clc.APIFailedResponse:
				raise
			except:
				e = clc.APIFailedResponse("Response code %s. %s. %s %s" %
				                         (r.status_code,r.text,method,fq_url))
				e.response_status_code = r.status_code
				e.response_json = {}	# or should this be None?
				e.response_text = r.text
				raise(e)
1256907
function processToken(token, done) {
    var user = _.find(users, function (item) {
        return item.username === token[claims.username];
    });
    if (!user) {
        user = {
            id          : token[claims.id] || currId++,
            username    : token[claims.username],
            email       : token[claims.email],
            firstName   : token[claims.firstName],
            lastName    : token[claims.lastName]
        };
        var roles = token[claims.role];
        if (!roles) {
            roles = ["guest"];
        } else if (!(roles instanceof Array)) {
            roles = [roles];
        }
        user.roles = roles;
        users.push(user);
    }
    done(null, user);
}
268734
function _auth (privateDirectoryUrl, publicUrl, jwksClient, cookieName, cookieDomain, forceExchange) {
  return asyncWrap(async (req, res, next) => {
    // JWT in a cookie = already active session
    const cookies = new Cookies(req, res)
    const token = _getCookieToken(cookies, req, cookieName, cookieDomain, publicUrl)
    if (token) {
      try {
        debug(`Verify JWT token from the ${cookieName} cookie`)
        req.user = await _verifyToken(jwksClient, token)
        _setOrganization(cookies, cookieName, req, req.user)
        debug('JWT token from cookie is ok', req.user)
      } catch (err) {
        // Token expired or bad in another way.. delete the cookie
        debug('JWT token from cookie is broken, clear it', err)
        cookies.set(cookieName, null, { domain: cookieDomain })
        cookies.set(cookieName + '_sign', null, { domain: cookieDomain })
        // case where the cookies were set before assigning domain
        if (cookies.get(cookieName)) {
          cookies.set(cookieName, null)
          cookies.set(cookieName + '_sign', null)
        }
      }
    }

    // We have a token from cookie
    // Does it need to be exchanged to prolongate the session ?
    if (req.user && req.user.exp) {
      debug('JWT token from cookie is set to expire on', new Date(req.user.exp * 1000))
      const timestamp = Date.now() / 1000
      // Token is more than 12 hours old or has less than half an hour left
      const tooOld = timestamp > (req.user.iat + 43200)
      const shortLife = timestamp > (req.user.exp - 1800)
      if (tooOld) debug('The token was issued more than 12 hours ago, exchange it for a new one')
      if (shortLife) debug('The token will expire in less than half an hour, exchange it for a new one')
      if (forceExchange) debug('The token was explicitly required to be exchanged (keepalive route), exchange it for a new one')
      if (tooOld || shortLife || forceExchange) {
        const exchangedToken = await _exchangeToken(privateDirectoryUrl, token)
        req.user = await _verifyToken(jwksClient, exchangedToken)
        _setOrganization(cookies, cookieName, req, req.user)
        debug('Exchanged token is ok, store it', req.user)
        _setCookieToken(cookies, cookieName, cookieDomain, exchangedToken, req.user)
      }
    }
    next()
  })
}
814127
def process_auth(self):
        
        r = self._reader
        w = self._writer
        pdu_size = r.get_smallint()
        if not self.authentication:
            raise tds_base.Error('Got unexpected token')
        packet = self.authentication.handle_next(readall(r, pdu_size))
        if packet:
            w.write(packet)
            w.flush()
865410
def restore_session
      guest_token, payment_method_id =
        params.fetch(:merchantReturnData).split("|")

      cookies.permanent.signed[:guest_token] = guest_token

      @payment_method = Spree::PaymentMethod.find(payment_method_id)

      @order = Spree::Order.find_by!(number: order_number)
    end
272033
def refresh_session(self, sessionkey, refresh_token=None):
        '''
        
        '''
        if not refresh_token:
            refresh_token = sessionkey
        params = {
            'appkey' : self.API_KEY,
            'sessionkey'  : sessionkey,
            'refresh_token': refresh_token
        }
        src = ''.join(["%s%s" % (k, v) for k, v in sorted(params.iteritems())]) + self.APP_SECRET
        params['sign'] = md5(src).hexdigest().upper()
        form_data = urllib.urlencode(params)
        rsp = requests.get('%s?%s'%(self.REFRESH_TOKEN_URL, form_data))
        rsp = json.loads(rsp.content)
        if 'error' in rsp:
            raise TOPException(rsp['error'], rsp['error_description'])
            return None
        rsp['re_expires_in'] = int(rsp['re_expires_in'])
        rsp['expires_in'] = int(rsp['expires_in'])
        rsp['session'] = rsp['top_session']
        del rsp['top_session']
        return rsp
1133254
def set_token(self, redirecturl):
        
        log.debug('Setting the token on %s.' % self.session)
        self.session.token_from_fragment(redirecturl)
76231
def get_session_token(self):
        '''  '''
        # HTTP POST query to session authenticate API
        try:
            response = requests.post(self.__session_url__ + 'sessionauth/v1/authenticate',
                                     cert=(self.__crt__, self.__key__), verify=True)
        except requests.exceptions.RequestException as err:
            self.logger.error(err)
            raise
        if response.status_code == 200:
            # load json response as list
            data = json.loads(response.text)
            self.logger.debug(data)
            # grab token from list
            session_token = data['token']
        else:
            raise Exception('BAD HTTP STATUS: %s' % str(response.status_code))
        # return the token
        self.logger.debug(session_token)
        return session_token
781901
private function get_access_token() {
        global $SESSION;
        if (isset($SESSION->{self::SESSIONKEY}) && $SESSION->{self::SESSIONKEY}) {
            $this->client->setAccessToken($SESSION->{self::SESSIONKEY});
            return $SESSION->{self::SESSIONKEY};
        }
        return null;
    }
479606
function readNotifyNewSession(message, tokens) {
	var i;
	message.userName = protocol.decodeString(tokens[1]);
	message.sessionId = protocol.decodeString(tokens[3]);
	message.contextProperties = {};
	tokens = tokens.slice(4);
	for (i = 0; i < tokens.length; i = i + 4) {
		message.contextProperties[protocol.decodeString(tokens[i + 1])] = protocol.decodeString(tokens[i + 3]);
	}
}
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;
		}
	}
510358
public static function getSessionToken()
    {
        $token = null;

        if (isset($_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'])) {
            $token = $_SESSION[__SYM_COOKIE_PREFIX__]['xsrf-token'];
        }

        if (is_array($token)) {
            $token = key($token);
        }

        return is_null($token) ? null : $token;
    }
772509
def update_token(self, token, secret):
        
        if self.access_token != token or self.secret != secret:
            with db.session.begin_nested():
                self.access_token = token
                self.secret = secret
                db.session.add(self)
424744
def generate_session_token(refresh_token, verbose):
    

    platform = _get_platform(authenticated=False)
    session_token, expires_in = platform.generate_session_token(refresh_token)

    if verbose:
        click.echo("%s\n\n%s" % (session_token, _color('YELLOW', "Expires in %d seconds" % expires_in)))
    else:
        click.echo(session_token)