parse signed request when using in-site app.

        Returns:
            dict object like { 'uid': 12345, 'access_token': 'ABC123XYZ', 'expires': unix-timestamp },
            or None if parse failed.
974113
def parse_signed_request(self, signed_request):
        '''
        
        '''
        def _b64_normalize(s):
            appendix = '=' * (4 - len(s) % 4)
            return s.replace('-', '+').replace('_', '/') + appendix

        sr = str(signed_request)
        logging.info('parse signed request: %s' % sr)
        enc_sig, enc_payload = sr.split('.', 1)
        sig = base64.b64decode(_b64_normalize(enc_sig))
        data = _parse_json(base64.b64decode(_b64_normalize(enc_payload)))
        if data['algorithm'] != u'HMAC-SHA256':
            return None
        expected_sig = hmac.new(self.client_secret, enc_payload, hashlib.sha256).digest()
        if expected_sig == sig:
            data.user_id = data.uid = data.get('user_id', None)
            data.access_token = data.get('oauth_token', None)
            expires = data.get('expires', None)
            if expires:
                data.expires = data.expires_in = time.time() + expires
            return data
        return None
843132
def _request_token(self, env):
        
        params = {}

        content = env['wsgi.input'].read(int(env['CONTENT_LENGTH']))
        post_params = parse_qs(content)
        # Convert to dict for easier access
        for param, value in post_params.items():
            decoded_param = param.decode('utf-8')
            decoded_value = value[0].decode('utf-8')
            if decoded_param == "username" or decoded_param == "password":
                params[decoded_param] = decoded_value

        params["grant_type"] = "password"
        params["client_id"] = self.client_id
        params["client_secret"] = self.client_secret
        # Request an access token by POSTing a request to the auth server.
        try:
            response = urllib2.urlopen(self.token_endpoint, urlencode(params))
        except HTTPError, he:
            if he.code == 400:
                error_body = json.loads(he.read())
                body = self.SERVER_ERROR_TEMPLATE\
                    .format(error_type=error_body["error"],
                            error_description=error_body["error_description"])
                return "400 Bad Request", body, {"Content-Type": "text/html"}
            if he.code == 401:
                return "302 Found", "", {"Location": "/login?failed=1"}

        self.token = json.load(response)

        return "301 Moved", "", {"Location": "/"}
1195036
def parse_token(self, token):
        
        try:
            data = self.unsign(token)
        except signing.SignatureExpired:
            logger.debug("Expired token: %s", token)
            return
        except signing.BadSignature:
            logger.debug("Bad token: %s", token)
            return
        except Exception:
            logger.exception(
                "Valid signature but unexpected token - if you changed "
                "django-sesame settings, you must regenerate tokens")
            return
        user_pk, data = self.packer.unpack_pk(data)
        user = self.get_user(user_pk)
        if user is None:
            logger.debug("Unknown token: %s", token)
            return
        h = crypto.pbkdf2(
            self.get_revocation_key(user),
            self.salt,
            self.iterations,
            digest=self.digest,
        )
        if not crypto.constant_time_compare(data, h):
            logger.debug("Invalid token: %s", token)
            return
        logger.debug("Valid token for user %s: %s", user, token)
        return user
400594
def _get_signed_url(self, params):
        
        params['client'] = self.client_id

        if self.channel:
            params['channel'] = self.channel

        path = "?".join((self.api_path, urlencode(params)))
        signature = hmac.new(
            base64.urlsafe_b64decode(self.secret_key),
            path.encode('utf-8'),
            hashlib.sha1
        )
        signature = base64.urlsafe_b64encode(
            signature.digest()
        ).decode('utf-8')
        return '%s://%s%s&signature=%s' % (
            self.scheme, self.domain, path, signature
        )
446201
def signed_uri(with_oauth = true)
      if signed?
        if with_oauth
          params = parameters
        else
          params = non_oauth_parameters
        end

        [uri, normalize(params)] * "?"
      else
        STDERR.puts "This request has not yet been signed!"
      end
    end
873377
def _sign_payload(self, payload):
        
        app_key = self._app_key
        t = int(time.time() * 1000)
        requestStr = {
            'header': self._req_header,
            'model': payload
        }
        data = json.dumps({'requestStr': json.dumps(requestStr)})
        data_str = '{}&{}&{}&{}'.format(self._req_token, t, app_key, data)
        sign = hashlib.md5(data_str.encode('utf-8')).hexdigest()
        params = {
            't': t,
            'appKey': app_key,
            'sign': sign,
            'data': data,
        }
        return params
584802
def get_token(url_base, tenant_id, user, password):
    
    url = 'http://' + url_base + '/v2.0/tokens'
    headers = {'Content-Type': 'application/json'}
    payload = '{"auth":{"tenantId":"' + tenant_id +\
              '","passwordCredentials":{"username":"'\
              + user + '","password":"' + password + '"}}}'
    response = requests.post(url, headers=headers, data=payload)
    if response.status_code != 200:
        print 'error to obtain the token ' + str(response.status_code)
        exit(1)
    response_json = response.json()
    token = response_json['access']['token']['id']
    return token
1343284
def verify_request_signature(request: RequestType, public_key: Union[str, bytes]):
    
    key = encode_if_text(public_key)
    date_header = request.headers.get("Date")
    if not date_header:
        raise ValueError("Rquest Date header is missing")

    ts = parse_http_date(date_header)
    dt = datetime.datetime.utcfromtimestamp(ts).replace(tzinfo=pytz.utc)
    delta = datetime.timedelta(seconds=30)
    now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
    if dt < now - delta or dt > now + delta:
        raise ValueError("Request Date is too far in future or past")

    HTTPSignatureHeaderAuth.verify(request, key_resolver=lambda **kwargs: key)
360711
def get_certificate_info():
    
    if hasattr(settings, 'MIT_WS_CERTIFICATE') and settings.MIT_WS_CERTIFICATE:
        mit_ws_certificate = settings.MIT_WS_CERTIFICATE
    else:
        return {"status": NO_CONFIG}

    app_cert = OpenSSL.crypto.load_certificate(
        OpenSSL.crypto.FILETYPE_PEM, (
            mit_ws_certificate if not isinstance(mit_ws_certificate, str)
            else mit_ws_certificate.encode().decode('unicode_escape').encode()
        )
    )

    app_cert_expiration = datetime.strptime(
        app_cert.get_notAfter().decode('ascii'),
        '%Y%m%d%H%M%SZ'
    )
    date_delta = app_cert_expiration - datetime.now()

    # if more then 30 days left in expiry of certificate then app is safe
    return {
        'app_cert_expires': app_cert_expiration.strftime('%Y-%m-%dT%H:%M:%S'),
        'status': UP if date_delta.days > 30 else DOWN
    }
792979
def request_token(self):
        
        logging.debug("Getting request token from %s:%d",
                      self.server, self.port)
        token, secret = self._token("/oauth/requestToken")
        return "{}/oauth/authorize?oauth_token={}".format(self.host, token), \
            token, secret
1311106
def uid(self):
        
        exp = datetime.datetime.utcnow() + self.expDelay
        claims = {
            'user_info': self.user_info,
            # Note that we use JWT standard 'exp' field to implement session expiration
            # we completely bypass twisted.web session expiration mechanisms
            'exp': calendar.timegm(datetime.datetime.timetuple(exp))}

        return jwt.encode(claims, self.site.session_secret, algorithm=SESSION_SECRET_ALGORITHM)
1199672
def access_token(self):
        
        if (self._access_token is None or
                self.expiration_time <= int(time.time())):
            resp = self.make_access_request()
            self._access_token = resp.json()['access_token']

        return self._access_token
133718
def get_signed_request(config, context, extension):
    
    url = "https://{hostname}/".format(hostname=get_signer_hostname())

    try:
        logger.debug("Requesting signed request URL from %s", url)
        response = requests.post(
            url,
            json={
                "arn": context.invoked_function_arn,
                "requestId": context.aws_request_id,
                "timestamp": int(time.time() * 1000),
                "extension": extension,
            },
            headers={"Authorization": config["token"]},
            timeout=config["network_timeout"],
        )
        response.raise_for_status()
    except Exception as e:
        logger.debug("Error requesting signed request URL: %s", e)
        if hasattr(e, "response"):
            logger.debug(e.response.content)
    else:
        response = response.json()
        logger.debug("Signed request URL received for %s", response["url"])
        return response
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))
529954
def token_of_request(
            self,
            method,
            host,
            url,
            qheaders,
            content_type=None,
            body=None):
        
        parsed_url = urlparse(url)
        netloc = parsed_url.netloc
        path = parsed_url.path
        query = parsed_url.query

        if not host:
            host = netloc

        path_with_query = path
        if query != '':
            path_with_query = ''.join([path_with_query, '?', query])
        data = ''.join(["%s %s" %
                        (method, path_with_query), "\n", "Host: %s" %
                        host, "\n"])

        if content_type:
            data += "Content-Type: %s" % (content_type) + "\n"

        data += qheaders
        data += "\n"

        if content_type and content_type != "application/octet-stream" and body:
            data += body.decode(encoding='UTF-8')

        return '{0}:{1}'.format(self.__access_key, self.__token(data))
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()
1046814
def parse_auth_token_from_request(self, auth_header):
        
        if not auth_header:
            raise falcon.HTTPUnauthorized(
                description='Missing Authorization Header')

        parts = auth_header.split()

        if parts[0].lower() != self.auth_header_prefix.lower():
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: '
                            'Must start with {0}'.format(self.auth_header_prefix))

        elif len(parts) == 1:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Token Missing')
        elif len(parts) > 2:
            raise falcon.HTTPUnauthorized(
                description='Invalid Authorization Header: Contains extra content')

        return parts[1]