コード例 #1
0
def _decode_jwt_from_request(request_type):
    # Check for the presence of _fake_token_callback and runs it instead of trying to retrieve token (provided app.debug is True)
    if has_fake_token_callback():
        if current_app.debug:
            return fake_token(request_type)
        else:
            import warnings
            warnings.warn(
                "ignoring _fake_token_callback, as app.debug is False")

    # We have three cases here, having jwts in both cookies and headers is
    # valid, or the jwt can only be saved in one of cookies or headers. Check
    # all cases here.
    if config.jwt_in_cookies and config.jwt_in_headers:
        try:
            decoded_token = _decode_jwt_from_cookies(request_type)
        except NoAuthorizationError:
            try:
                decoded_token = _decode_jwt_from_headers()
            except NoAuthorizationError:
                raise NoAuthorizationError(
                    "Missing JWT in headers and cookies")
    elif config.jwt_in_headers:
        decoded_token = _decode_jwt_from_headers()
    else:
        decoded_token = _decode_jwt_from_cookies(request_type)

    # Make sure the type of token we received matches the request type we expect
    verify_token_type(decoded_token, expected_type=request_type)

    # If blacklisting is enabled, see if this token has been revoked
    verify_token_not_blacklisted(decoded_token, request_type)

    return decoded_token
コード例 #2
0
def _decode_jwt_from_request(request_type):
    # We have three cases here, having jwts in both cookies and headers is
    # valid, or the jwt can only be saved in one of cookies or headers. Check
    # all cases here.
    if config.jwt_in_cookies and config.jwt_in_headers:
        try:
            decoded_token = _decode_jwt_from_cookies(request_type)
        except NoAuthorizationError:
            try:
                decoded_token = _decode_jwt_from_headers()
            except NoAuthorizationError:
                raise NoAuthorizationError(
                    "Missing JWT in headers and cookies")
    elif config.jwt_in_headers:
        decoded_token = _decode_jwt_from_headers()
    else:
        decoded_token = _decode_jwt_from_cookies(request_type)

    # Make sure the type of token we received matches the request type we expect
    verify_token_type(decoded_token, expected_type=request_type)

    # If blacklisting is enabled, see if this token has been revoked
    verify_token_not_blacklisted(decoded_token, request_type)

    return decoded_token
コード例 #3
0
def decode_jwt_from_json(request, request_type, allow_missing_token=False):
    if request.content_type != 'application/json':
        raise NoAuthorizationError(
            'Invalid content-type. Must be application/json.')

    if request_type == 'access':
        token_key = 'access_token'
    else:
        token_key = 'refresh_token'

    try:
        encoded_token = request.get_json().get(token_key)
        if not encoded_token:
            if allow_missing_token:
                return None
            else:
                raise BadRequest()
    except BadRequest:
        raise NoAuthorizationError(
            'Missing "{}" key in json data.'.format(token_key))

    decoded_token = None
    decoded_token = decode_token(encoded_token, None)
    verify_token_type(decoded_token, expected_type=request_type)
    verify_token_not_blacklisted(decoded_token, request_type)
    return decoded_token
コード例 #4
0
 def check_token(self, token):
     """检测token是否存在"""
     try:
         decoded_token = decode_token(token)
         verify_token_not_blacklisted(decoded_token, "access")
         email = decoded_token["identity"]
         self.user_hash = encrypt_str(email)
         return True
     except RevokedTokenError:
         return False
     except DecodeError:
         return False
コード例 #5
0
ファイル: view_decorators.py プロジェクト: otr0624/StoreApp
def _decode_jwt_from_request(request_type):
    # All the places we can get a JWT from in this request
    get_encoded_token_functions = []

    locations = config.token_location

    # add the functions in the order specified in JWT_TOKEN_LOCATION
    for location in locations:
        if location == "cookies":
            get_encoded_token_functions.append(
                lambda: _decode_jwt_from_cookies(request_type))
        if location == "query_string":
            get_encoded_token_functions.append(_decode_jwt_from_query_string)
        if location == "headers":
            get_encoded_token_functions.append(_decode_jwt_from_headers)
        if location == "json":
            get_encoded_token_functions.append(
                lambda: _decode_jwt_from_json(request_type))

    # Try to find the token from one of these locations. It only needs to exist
    # in one place to be valid (not every location).
    errors = []
    decoded_token = None
    jwt_header = None
    for get_encoded_token_function in get_encoded_token_functions:
        try:
            encoded_token, csrf_token = get_encoded_token_function()
            decoded_token = decode_token(encoded_token, csrf_token)
            jwt_header = get_unverified_jwt_headers(encoded_token)
            break
        except NoAuthorizationError as e:
            errors.append(str(e))

    # Do some work to make a helpful and human readable error message if no
    # token was found in any of the expected locations.
    if not decoded_token:
        token_locations = config.token_location
        multiple_jwt_locations = len(token_locations) != 1

        if multiple_jwt_locations:
            err_msg = "Missing JWT in {start_locs} or {end_locs} ({details})".format(
                start_locs=", ".join(token_locations[:-1]),
                end_locs=token_locations[-1],
                details="; ".join(errors),
            )
            raise NoAuthorizationError(err_msg)
        else:
            raise NoAuthorizationError(errors[0])

    verify_token_type(decoded_token, expected_type=request_type)
    verify_token_not_blacklisted(decoded_token, request_type)
    return decoded_token, jwt_header
コード例 #6
0
def _decode_jwt_from_request(request_type):
    # All the places we can get a JWT from in this request
    get_encoded_token_functions = []
    if config.jwt_in_cookies:
        get_encoded_token_functions.append(
            lambda: _decode_jwt_from_cookies(request_type))
    if config.jwt_in_query_string:
        get_encoded_token_functions.append(_decode_jwt_from_query_string)
    if config.jwt_in_headers:
        get_encoded_token_functions.append(_decode_jwt_from_headers)
    if config.jwt_in_json:
        get_encoded_token_functions.append(
            lambda: _decode_jwt_from_json(request_type))

    # Try to find the token from one of these locations. It only needs to exist
    # in one place to be valid (not every location).
    errors = []
    decoded_token = None
    for get_encoded_token_function in get_encoded_token_functions:
        try:
            encoded_token, csrf_token = get_encoded_token_function()
            decoded_token = decode_token(encoded_token, csrf_token)
            break
        except ExpiredSignatureError:
            # Save the expired token so we can access it in a callback later
            expired_data = decode_token(encoded_token,
                                        csrf_token,
                                        allow_expired=True)
            ctx_stack.top.expired_jwt = expired_data
            raise
        except NoAuthorizationError as e:
            errors.append(str(e))

    # Do some work to make a helpful and human readable error message if no
    # token was found in any of the expected locations.
    if not decoded_token:
        token_locations = config.token_location
        multiple_jwt_locations = len(token_locations) != 1

        if multiple_jwt_locations:
            err_msg = "Missing JWT in {start_locs} or {end_locs} ({details})".format(
                start_locs=", ".join(token_locations[:-1]),
                end_locs=token_locations[-1],
                details="; ".join(errors))
            raise NoAuthorizationError(err_msg)
        else:
            raise NoAuthorizationError(errors[0])

    verify_token_type(decoded_token, expected_type=request_type)
    verify_token_not_blacklisted(decoded_token, request_type)
    return decoded_token
コード例 #7
0
def get_user_token(encoded_token, token_type):
    from flask_jwt_extended.exceptions import NoAuthorizationError, UserLoadError
    from flask_jwt_extended import utils as jwt_utils
    from flask_jwt_extended.config import config as jwt_config

    if encoded_token is None:
        raise NoAuthorizationError('Missing "access_token" query parameter')

    token_data = decode_token(encoded_token)
    jwt_utils.verify_token_type(token_data, expected_type=token_type)
    jwt_utils.verify_token_not_blacklisted(token_data, token_type)
    jwt_utils.verify_token_claims(token_data)

    return token_data[jwt_config.identity_claim_key]
コード例 #8
0
def verify_jwt_token(encoded_token, token_type):
    from flask_jwt_extended.exceptions import NoAuthorizationError, UserLoadError
    from flask_jwt_extended import utils as jwt_utils
    from flask_jwt_extended.config import config as jwt_config

    if encoded_token is None:
        raise NoAuthorizationError('Missing "access_token" query parameter')

    token_data = decode_token(encoded_token)
    jwt_utils.verify_token_type(token_data, expected_type=token_type)
    jwt_utils.verify_token_not_blacklisted(token_data, token_type)
    jwt_utils.verify_token_claims(token_data)

    identity = token_data[jwt_config.identity_claim_key]
    if jwt_utils.has_user_loader():
        user = jwt_utils.user_loader(identity)
        if user is None:
            raise UserLoadError(
                "user_loader returned None for {}".format(identity))
コード例 #9
0
    def is_accessible(self):
        try:

            token = request.args.get("jwt")
            if not token:
                token = urllib.parse.parse_qsl(request.args.get("url"))[0][1]
            decoded_token = decode_token(token)
            verify_token_not_blacklisted(decoded_token, request_type="access")
            ctx_stack.top.jwt = decoded_token
            if has_user_loader():
                user = user_loader(ctx_stack.top.jwt["identity"])
                if user is None:
                    raise UserLoadError(
                        "user_loader returned None for {}".format(user))
                ctx_stack.top.jwt_user = user

            current_user = get_jwt_identity()
            is_admin = UserModel.query.filter_by(
                username=current_user).one().admin
            return current_user and is_admin
        except Exception as e:
            current_app.logger.critical("FAULTY ADMIN UI ACCESS: %s", str(e))
            return False