Internal helper to retrieve the deprecated set of JWT_ISSUER data from the JWT_AUTH configuration
    Having this allows for easier testing/mocking
327531
def _get_deprecated_jwt_issuers():
    
    # If JWT_ISSUERS is not defined, attempt to return the deprecated settings.
    warnings.warn(
        "'JWT_ISSUERS' list not defined, checking for deprecated settings.",
        DeprecationWarning
    )

    return [
        {
            'ISSUER': api_settings.JWT_ISSUER,
            'SECRET_KEY': api_settings.JWT_SECRET_KEY,
            'AUDIENCE': api_settings.JWT_AUDIENCE
        }
    ]
1129084
def jwt_proccessor():
    """"""
    def jwt():
        """Context processor function to generate jwt."""
        token = current_accounts.jwt_creation_factory()
        return Markup(
            render_template(
                current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
                token=token
            )
        )

    def jwt_token():
        """Context processor function to generate jwt."""
        return current_accounts.jwt_creation_factory()

    return {
        'jwt': jwt,
        'jwt_token': jwt_token,
    }
601182
def authenticate_credentials(self, payload):
        """"""
        username = payload.get('preferred_username') or payload.get('username')

        if username is None:
            raise exceptions.AuthenticationFailed('JWT must include a preferred_username or username claim!')
        else:
            try:
                user, __ = get_user_model().objects.get_or_create(username=username)
                attributes_updated = False
                for claim, attr in self.get_jwt_claim_attribute_map().items():
                    payload_value = payload.get(claim)

                    if getattr(user, attr) != payload_value and payload_value is not None:
                        setattr(user, attr, payload_value)
                        attributes_updated = True

                if attributes_updated:
                    user.save()
            except:
                msg = 'User retrieval failed.'
                logger.exception(msg)
                raise exceptions.AuthenticationFailed(msg)

        return user
330990
def _validate_jwt_data(self, data, access_type):
        
        MissingClaimError.require_condition(
            'jti' in data,
            'Token is missing jti claim',
        )
        BlacklistedError.require_condition(
            not self.is_blacklisted(data['jti']),
            'Token has a blacklisted jti',
        )
        MissingClaimError.require_condition(
            'id' in data,
            'Token is missing id field',
        )
        MissingClaimError.require_condition(
            'exp' in data,
            'Token is missing exp claim',
        )
        MissingClaimError.require_condition(
            'rf_exp' in data,
            'Token is missing rf_exp claim',
        )
        moment = pendulum.now('UTC').int_timestamp
        if access_type == AccessType.access:
            ExpiredAccessError.require_condition(
                moment <= data['exp'],
                'access permission has expired',
            )
        elif access_type == AccessType.refresh:
            EarlyRefreshError.require_condition(
                moment > data['exp'],
                'access permission for token has not expired. may not refresh',
            )
            ExpiredRefreshError.require_condition(
                moment <= data['rf_exp'],
                'refresh permission for token has expired',
            )
839784
def authenticate(self, request):
        
        jwt_value = self.get_jwt_value(request)
        if jwt_value is None:
            return None

        try:
            payload = jwt_decode_handler(jwt_value)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)

        return (user, jwt_value)
1056212
def get_jwt_data_from_app_context():
    
    ctx = flask._app_ctx_stack.top
    jwt_data = getattr(ctx, 'jwt_data', None)
    PraetorianError.require_condition(
        jwt_data is not None,
        """
        No jwt_data found in app context.
        Make sure @auth_required decorator is specified *first* for route
        """,
    )
    return jwt_data
725825
function getHeaders(authRequired = false) {
    if (!authRequired)
        return exports.basicHeaders;
    if ((!('X-Auth-Token' in exports.authHeaders) || !('X-User-Id' in exports.authHeaders)) ||
        exports.authHeaders['X-Auth-Token'] === '' ||
        exports.authHeaders['X-User-Id'] === '') {
        throw new Error('Auth required endpoint cannot be called before login');
    }
    return Object.assign({}, exports.basicHeaders, exports.authHeaders);
}
841122
def _get_signing_jwk_key_set(jwt_issuer):
    
    key_set = KEYS()

    # asymmetric keys
    signing_jwk_set = settings.JWT_AUTH.get('JWT_PUBLIC_SIGNING_JWK_SET')
    if signing_jwk_set:
        key_set.load_jwks(signing_jwk_set)

    # symmetric key
    key_set.add({'key': jwt_issuer['SECRET_KEY'], 'kty': 'oct'})

    return key_set
142884
def auth_request_handler(self, callback):
        
        warnings.warn("This handler is deprecated. The recommended approach to have control over "
                      "the authentication resource is to disable the built-in  resource by "
                      "setting JWT_AUTH_URL_RULE=None and registering your own authentication "
                      "resource directly on your application.", DeprecationWarning, stacklevel=2)
        self.auth_request_callback = callback
        return callback
802470
function init(config) {
    var tokenConfig = config.security.token || {};
    var privateKey = tokenConfig.privateKey;
    var decryptedToken = {
        _id: tokenConfig.webserverId,
        authToken: tokenConfig.webserverToken
    };
    var jwt = jsonwebtoken.sign(decryptedToken, privateKey);

    headers = { 'Authorization': 'Bearer ' + jwt };

    admin._id =  mongo.newObjectId('000000000000000000000000');
    admin.name = 'systemAdmin';
    admin.type = 'user';
    admin.role = 'admin';

    var apiConfig = config.api || {};
    var host = apiConfig.internalHost || apiConfig.host;  // from web server to api use internalHost name
    var useSSL = apiConfig.serverUseSSL !== undefined ?
        apiConfig.serverUseSSL : config.useSSL;
    baseUrl = (useSSL ? 'https://' : 'http://') + host;

    var port = config.api.port;
    if (port !== 80 && port !== 443) {
        baseUrl += ':' + port;
    }

    baseUrl += '/' + config.api.version;

    return config;
}
874666
def build_preauth_str(preauth_key, account_name, timestamp, expires,
                      admin=False):
    
    if admin:
        s = '{0}|1|name|{1}|{2}'.format(account_name, expires, timestamp)
    else:
        s = '{0}|name|{1}|{2}'.format(account_name, expires, timestamp)

    return hmac.new(preauth_key.encode('utf-8'), s.encode('utf-8'),
                    hashlib.sha1).hexdigest()
210329
def unpack(self, token):
        
        if not token:
            raise KeyError

        _jwe_header = _jws_header = None

        # Check if it's an encrypted JWT
        darg = {}
        if self.allowed_enc_encs:
            darg['enc'] = self.allowed_enc_encs
        if self.allowed_enc_algs:
            darg['alg'] = self.allowed_enc_algs
        try:
            _decryptor = jwe_factory(token, **darg)
        except (KeyError, HeaderError):
            _decryptor = None

        if _decryptor:
            # Yes, try to decode
            _info = self._decrypt(_decryptor, token)
            _jwe_header = _decryptor.jwt.headers
            # Try to find out if the information encrypted was a signed JWT
            try:
                _content_type = _decryptor.jwt.headers['cty']
            except KeyError:
                _content_type = ''
        else:
            _content_type = 'jwt'
            _info = token

        # If I have reason to believe the information I have is a signed JWT
        if _content_type.lower() == 'jwt':
            # Check that is a signed JWT
            if self.allowed_sign_algs:
                _verifier = jws_factory(_info, alg=self.allowed_sign_algs)
            else:
                _verifier = jws_factory(_info)

            if _verifier:
                _info = self._verify(_verifier, _info)
            else:
                raise Exception()
            _jws_header = _verifier.jwt.headers
        else:
            # So, not a signed JWT
            try:
                # A JSON document ?
                _info = json.loads(_info)
            except JSONDecodeError:  # Oh, no ! Not JSON
                return _info
            except TypeError:
                try:
                    _info = as_unicode(_info)
                    _info = json.loads(_info)
                except JSONDecodeError:  # Oh, no ! Not JSON
                    return _info

        # If I know what message class the info should be mapped into
        if self.msg_cls:
            _msg_cls = self.msg_cls
        else:
            try:
                # try to find a issuer specific message class
                _msg_cls = self.iss2msg_cls[_info['iss']]
            except KeyError:
                _msg_cls = None

        if _msg_cls:
            vp_args = {'skew': self.skew}
            if self.iss:
                vp_args['aud'] = self.iss
            _info = self.verify_profile(_msg_cls, _info, **vp_args)
            _info.jwe_header = _jwe_header
            _info.jws_header = _jws_header
            return _info
        else:
            return _info
566561
def get_auth_token(self, user_payload):
        
        now = datetime.utcnow()
        payload = {
            'user': user_payload
        }
        if 'iat' in self.verify_claims:
            payload['iat'] = now

        if 'nbf' in self.verify_claims:
            payload['nbf'] = now + self.leeway

        if 'exp' in self.verify_claims:
            payload['exp'] = now + self.expiration_delta

        if self.audience is not None:
            payload['aud'] = self.audience

        if self.issuer is not None:
            payload['iss'] = self.issuer

        return jwt.encode(
            payload,
            self.secret_key,
            algorithm=self.algorithm,
            json_encoder=ExtendedJSONEncoder).decode('utf-8')
709563
function _getAuthorizationToken() {
    return spinner(
        new Promise((resolve, reject) =>
            ECR.sdk
                .getAuthorizationToken({})
                .promise()
                .then(data => {
                    if (!_.has(data, 'authorizationData.0')) {
                        reject(new Error('No authorization data found.'));
                        return;
                    }
                    resolve(data.authorizationData[0]);
                })
        )
    );
}
225110
def get_jwt_key_data():
    
    global __jwt_data

    if __jwt_data:
        return __jwt_data

    from cloud_inquisitor import config_path
    from cloud_inquisitor.config import dbconfig

    jwt_key_file = dbconfig.get('jwt_key_file_path', default='ssl/private.key')
    if not os.path.isabs(jwt_key_file):
        jwt_key_file = os.path.join(config_path, jwt_key_file)

    with open(os.path.join(jwt_key_file), 'r') as f:
        __jwt_data = f.read()

    return __jwt_data
197616
def get_payload_data(self, token, key):
        """"""
        if self.get_settings('OIDC_ALLOW_UNSECURED_JWT', False):
            header, payload_data, signature = token.split(b'.')
            header = json.loads(smart_text(b64decode(header)))

            # If config allows unsecured JWTs check the header and return the decoded payload
            if 'alg' in header and header['alg'] == 'none':
                return b64decode(payload_data)

        # By default fallback to verify JWT signatures
        return self._verify_jws(token, key)
242329
def verify_fresh_jwt_in_request():
    
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        fresh = jwt_data['fresh']
        if isinstance(fresh, bool):
            if not fresh:
                raise FreshTokenRequired('Fresh token required')
        else:
            now = timegm(datetime.utcnow().utctimetuple())
            if fresh < now:
                raise FreshTokenRequired('Fresh token required')
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])