Extract payload field from JWT.

        Args:
            access_token (str): Access token to decode. Defaults to ``None``.

        Returns:
            dict: JSON object that contains the claims conveyed by the JWT.
506427
def decode_jwt_payload(self, access_token=None):
        
        c = self.get_credentials()
        jwt = access_token or c.access_token
        try:
            _, payload, _ = jwt.split('.')  # header, payload, sig
            rem = len(payload) % 4
            if rem > 0:  # add padding
                payload += '=' * (4 - rem)
            try:
                decoded_jwt = b64decode(payload).decode("utf-8")
            except TypeError as e:
                raise PanCloudError(
                    "Failed to base64 decode JWT: %s" % e)
            else:
                try:
                    x = loads(decoded_jwt)
                except ValueError as e:
                    raise PanCloudError("Invalid JSON: %s" % e)
        except (AttributeError, ValueError) as e:
            raise PanCloudError("Invalid JWT: %s" % e)

        return x
412581
def fetch_access_token(self):
        
        return self._fetch_access_token(
            url='https://qyapi.weixin.qq.com/cgi-bin/gettoken',
            params={
                'corpid': self.corp_id,
                'corpsecret': self.secret
            }
        )
587108
def get_auth_token(self, user_payload):
        
        username = user_payload.get('username') or None
        password = user_payload.get('password') or None

        if not username or not password:
            raise ValueError('`user_payload` must contain both username and password')

        token = '{username}:{password}'.format(
            username=username, password=password).encode('utf-8')

        token_b64 = base64.b64encode(token).decode('utf-8', 'ignore')

        return '{auth_header_prefix} {token_b64}'.format(
            auth_header_prefix=self.auth_header_prefix, token_b64=token_b64)
39512
def extract_payload(self):
        """"""
        if not self.check_signature():
            raise InvalidSignature('Invalid Signature')
        if request.is_json:
            # Request.get_json() could be first called with silent=True.
            delete_cached_json_for(request)
            return request.get_json(silent=False, cache=False)
        elif request.content_type == 'application/x-www-form-urlencoded':
            return dict(request.form)
        raise InvalidPayload(request.content_type)
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')
906476
def _parse_access_token(self, resp_text):
        '  '
        r = self._qs2dict(resp_text)
        access_token = r.pop('access_token')
        expires = time.time() + float(r.pop('expires_in'))
        return JsonDict(access_token=access_token, expires=expires, **r)
757239
def lookup_accessor(accessor, options = {})
      headers = extract_headers!(options)
      json = client.post("/v1/auth/token/lookup-accessor", JSON.fast_generate(
        accessor: accessor,
      ), headers)
      return Secret.decode(json)
    end
682783
def get_token_payload(token)

        # Attempt to decode without verifying. May raise DecodeError.
        decoded = JWT.decode token, nil, false
        payload = decoded[0]

        # At this point, we know that the token is not expired and
        # well formatted. Find out if the payload is well defined.
        if payload.nil?
          # :nocov:
          logger.error("Token payload is nil: #{token}")
          raise UNAUTHORIZED_ERROR, "Invalid token"
          # :nocov:
        end

        return payload

      rescue JWT::DecodeError => e
        logger.error("Token decode error: #{e.message}")
        raise UNAUTHORIZED_ERROR, "Invalid token"
      end
1155681
def access_token(self):
        """"""
        if self.cache_token:
            return self.access_token_ or \
                   self._resolve_credential('access_token')
        return self.access_token_
181237
def _make_jwt(self):
        
        now = _helpers.utcnow()
        lifetime = datetime.timedelta(seconds=self._token_lifetime)
        expiry = now + lifetime

        payload = {
            'iss': self._issuer,
            'sub': self._subject,
            'iat': _helpers.datetime_to_secs(now),
            'exp': _helpers.datetime_to_secs(expiry),
            'aud': self._audience,
        }

        payload.update(self._additional_claims)

        jwt = encode(self._signer, payload)

        return jwt, expiry
764938
def get_id_token(self, access_token, nonce):
        

        claims_string = self.request.POST.get('claims')
        claims_request = json.loads(claims_string) if claims_string else {}

        return oidc.id_token(access_token, nonce, claims_request)
1370302
def get_access_token(self, code=None, **params):
        
        if self._access_token is None:
            if code is None:
                raise ValueError(_('Invalid code.'))
            
            self.access_token_dict = self._get_access_token(code, **params)
            try:
                self._access_token = self.access_token_dict['access_token']
            except KeyError, e:
                raise OAuthError("Credentials could not be validated, the provider returned no access token.")
                
        return self._access_token
803305
def to_dict(self):
        
        return {'access_key': self.access_key,
                'secret_key': self.secret_key,
                'session_token': self.session_token,
                'expiration': self.expiration,
                'request_id': self.request_id}
78645
def authenticate_credentials(self, payload):
        
        try:
            user_id = jwt_get_user_id_from_payload(payload)

            if user_id:
                user = User.objects.get(pk=user_id, is_active=True)
            else:
                msg = 'Invalid payload'
                raise exceptions.AuthenticationFailed(msg)
        except User.DoesNotExist:
            msg = 'Invalid signature'
            raise exceptions.AuthenticationFailed(msg)

        return user
1066720
def get_JWT(url, address=None):
    
    jwt_txt = None
    jwt = None

    log.debug("Try {}".format(url))

    # special case: handle file://
    urlinfo = urllib2.urlparse.urlparse(url)
    if urlinfo.scheme == 'file':
        # points to a path on disk
        try:
            with open(urlinfo.path, 'r') as f:
                jwt_txt = f.read()

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Failed to read {}".format(url))
            return None

    else:
        # http(s) URL or similar
        try:
            resp = requests.get(url)
            assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
            jwt_txt = resp.text

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Unable to resolve {}".format(url))
            return None

    try:
        # one of two things are possible:
        # * this is a JWT string
        # * this is a serialized JSON string whose first item is a dict that has 'token' as key,
        # and that key is a JWT string.
        try:
            jwt_txt = json.loads(jwt_txt)[0]['token']
        except:
            pass

        jwt = jsontokens.decode_token(jwt_txt)
    except Exception as e:
        if BLOCKSTACK_TEST:
            log.exception(e)

        log.warning("Unable to decode token at {}".format(url))
        return None

    try:
        # must be well-formed
        assert isinstance(jwt, dict)
        assert 'payload' in jwt, jwt
        assert isinstance(jwt['payload'], dict)
        assert 'issuer' in jwt['payload'], jwt
        assert isinstance(jwt['payload']['issuer'], dict)
        assert 'publicKey' in jwt['payload']['issuer'], jwt
        assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))

    except AssertionError as ae:
        if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
            log.exception(ae)

        log.warning("JWT at {} is malformed".format(url))
        return None

    if address is not None:
        public_key = str(jwt['payload']['issuer']['publicKey'])
        addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
                 virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]

        if virtualchain.address_reencode(address) not in addrs:
            # got a JWT, but it doesn't match the address
            log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
            return None

        verifier = jsontokens.TokenVerifier()
        if not verifier.verify(jwt_txt, public_key):
            # got a JWT, and the address matches, but the signature does not
            log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
            return None

    return jwt
474215
def parse_auth_token(self, auth_token):
        
        # remove the random security key value from the front of the auth_token
        auth_token_cleaned = auth_token.split('-', 1)[1]
        # URL Decode the Auth Token
        auth_token_decoded = self.url_decode(auth_token_cleaned)
        # Create a new dict to hold the response.
        auth_dict = {}

        # Parse the token
        for key_value in auth_token_decoded.split("&"):
            key_value_list = key_value.split("=")
            # check for valid token parts
            if len(key_value_list) == 2 and type(key_value_list[0]) in [text_type, binary_type]:
                auth_dict[key_value_list[0]] = key_value_list[1]

        # Return the dict of key/values in the token.
        return auth_dict
1262843
def request_access_token(self, access_code):
        ""
        token_response = request_session.post(
            "https://github.com/login/oauth/access_token",
            data={
                "client_id": self.oauth_client_id,
                "client_secret": self.oauth_client_secret,
                "code": access_code
            },
            headers={"Accept": "application/json"},
        )
        return helper_request_access_token(token_response.json())