示例#1
0
def auth_lg_1(*args, **kw):
    username = get_jwt_identity()
    user_login = UserLogins.query.filter_by(username=username).first()
    if user_login is None:
        raise NoAuthorizationError(u"请先登陆")
    elif user_login.level < 2:
        raise NoAuthorizationError(u'您没有足够的权限进行此操作!')
示例#2
0
        def wrapper(*args, **kwargs):
            isUserAuthorized = False
            search_option = {
                'full_document': True,
                'filter': {
                    'fliptapikey': {
                        'type': 'eq',
                        'value': auth.username(),
                        'case_sensitive': False
                    }
                },
                'filter_type': 'and'
            }
            userattribute, userid = OptionalModules.user().search_tvuser(
                search_option)
            if userid == None:
                isUserAuthorized = False
            else:
                isUserAuthorized = True

            if not isUserAuthorized:
                raise NoAuthorizationError(
                    "You are not authorized user to access the API")

            if not userattribute['status'] == 'Active':
                raise NoAuthorizationError("Your account is Inactive")

            return apifunction(userattribute)
示例#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
def _decode_jwt_from_request(locations, fresh, refresh=False):
    # Figure out what locations to look for the JWT in this request
    if isinstance(locations, str):
        locations = [locations]

    if not locations:
        locations = config.token_location

    # Get the decode functions in the order specified by locations.
    get_encoded_token_functions = []
    for location in locations:
        if location == "cookies":
            get_encoded_token_functions.append(
                lambda: _decode_jwt_from_cookies(refresh))
        elif location == "query_string":
            get_encoded_token_functions.append(_decode_jwt_from_query_string)
        elif location == "headers":
            get_encoded_token_functions.append(_decode_jwt_from_headers)
        elif location == "json":
            get_encoded_token_functions.append(
                lambda: _decode_jwt_from_json(refresh))
        else:
            raise RuntimeError(f"'{location}' is not a valid location")

    # 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:
        if len(locations) > 1:
            err_msg = "Missing JWT in {start_locs} or {end_locs} ({details})".format(
                start_locs=", ".join(locations[:-1]),
                end_locs=locations[-1],
                details="; ".join(errors),
            )
            raise NoAuthorizationError(err_msg)
        else:
            raise NoAuthorizationError(errors[0])

    # Additional verifications provided by this extension
    verify_token_type(decoded_token, refresh)
    if fresh:
        _verify_token_is_fresh(jwt_header, decoded_token)
    verify_token_not_blocklisted(jwt_header, decoded_token)
    custom_verification_for_token(jwt_header, decoded_token)

    return decoded_token, jwt_header
def _decode_jwt_from_request(token_type, locations, fresh):
    # All the places we can get a JWT from in this request
    get_encoded_token_functions = []

    # Get locations in the order specified by the decorator or JWT_TOKEN_LOCATION
    # configuration.
    if not locations:
        locations = config.token_location

    # Add the functions in the order specified by locations.
    for location in locations:
        if location == "cookies":
            get_encoded_token_functions.append(
                lambda: _decode_jwt_from_cookies(token_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(token_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:
        if len(locations) > 1:
            err_msg = "Missing JWT in {start_locs} or {end_locs} ({details})".format(
                start_locs=", ".join(locations[:-1]),
                end_locs=locations[-1],
                details="; ".join(errors),
            )
            raise NoAuthorizationError(err_msg)
        else:
            raise NoAuthorizationError(errors[0])

    # Additional verifications provided by this extension
    verify_token_type(decoded_token, expected_type=token_type)
    if fresh:
        _verify_token_is_fresh(jwt_header, decoded_token)
    verify_token_not_blocklisted(jwt_header, decoded_token, token_type)
    custom_verification_for_token(jwt_header, decoded_token)

    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 = []

    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
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
示例#8
0
def _decode_jwt_from_cookies(refresh):
    if refresh:
        cookie_key = config.refresh_cookie_name
        csrf_header_key = config.refresh_csrf_header_name
        csrf_field_key = config.refresh_csrf_field_name
    else:
        cookie_key = config.access_cookie_name
        csrf_header_key = config.access_csrf_header_name
        csrf_field_key = config.access_csrf_field_name

    encoded_token = request.cookies.get(cookie_key)
    if not encoded_token:
        raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key))

    if (config.csrf_protect and request.method in config.csrf_request_methods
            and current_app.config["JWT_CSRF_ACCESS_PATH"] in request.url):
        csrf_value = request.headers.get(csrf_header_key, None)
        if not csrf_value and config.csrf_check_form:
            csrf_value = request.form.get(csrf_field_key, None)
        if not csrf_value:
            raise CSRFError("Missing CSRF token")
    else:
        csrf_value = None

    return encoded_token, csrf_value
示例#9
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request()
     claims = get_jwt_claims()
     if 'admin' not in claims['roles']:
         raise NoAuthorizationError("Permission Denied!")
     else:
         return fn(*args, **kwargs)
示例#10
0
def _decode_jwt_from_cookies(request_type):
    if request_type == 'access':
        cookie_key = config.access_cookie_name
        csrf_header_key = config.access_csrf_header_name
        csrf_field_key = config.access_csrf_field_name
        csrf_cookie_name = config.access_csrf_cookie_name
    else:
        cookie_key = config.refresh_cookie_name
        csrf_header_key = config.refresh_csrf_header_name
        csrf_field_key = config.refresh_csrf_field_name
        csrf_cookie_name = config.refresh_csrf_cookie_name

    encoded_token = request.cookies.get(cookie_key)
    if not encoded_token:
        raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key))

    if config.csrf_protect and request.method in config.csrf_request_methods:
        csrf_value = request.headers.get(csrf_header_key, None)
        if not csrf_value and config.csrf_check_cookies:
            csrf_value = request.cookies.get(csrf_cookie_name, None)
        if not csrf_value and config.csrf_check_form:
            csrf_value = request.form.get(csrf_field_key, None)
        if not csrf_value:
            raise CSRFError("Missing CSRF token")
    else:
        csrf_value = None

    return encoded_token, csrf_value
示例#11
0
def _decode_jwt_from_query_string():
    query_param = config.query_string_name
    encoded_token = request.args.get(query_param)
    if not encoded_token:
        raise NoAuthorizationError('Missing "{}" query paramater'.format(query_param))

    return decode_token(encoded_token)
示例#12
0
def _decode_jwt_from_cookies(type):
    if type == 'access':
        cookie_key = get_access_cookie_name()
    else:
        cookie_key = get_refresh_cookie_name()

    token = request.cookies.get(cookie_key)
    if not token:
        raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key))
    secret = _get_secret_key()
    algorithm = get_algorithm()
    token = _decode_jwt(token, secret, algorithm)

    if get_cookie_csrf_protect(
    ) and request.method in get_csrf_request_methods():
        csrf_header_key = get_csrf_header_name()
        csrf_token_from_header = request.headers.get(csrf_header_key, None)
        csrf_token_from_cookie = token.get('csrf', None)

        # Verify the csrf tokens are present and matching
        if csrf_token_from_cookie is None:
            raise JWTDecodeError("Missing claim: 'csrf'")
        if not isinstance(csrf_token_from_cookie, six.string_types):
            raise JWTDecodeError("Invalid claim: 'csrf' (must be a string)")
        if csrf_token_from_header is None:
            raise CSRFError("Missing CSRF token in headers")
        if not safe_str_cmp(csrf_token_from_header, csrf_token_from_cookie):
            raise CSRFError("CSRF double submit tokens do not match")
    return token
示例#13
0
def _decode_jwt_from_headers():
    # Verify we have the auth header
    header_name = get_jwt_header_name()
    jwt_header = request.headers.get(header_name, None)
    if not jwt_header:
        raise NoAuthorizationError("Missing {} Header".format(header_name))

    # Make sure the header is valid
    expected_header = get_jwt_header_type()
    parts = jwt_header.split()
    if not expected_header:
        if len(parts) != 1:
            msg = "Bad {} header. Expected '<JWT>'"
            raise InvalidHeaderError(msg)
        token = parts[0]
    else:
        if parts[0] != expected_header or len(parts) != 2:
            msg = "Bad {} header. Expected '{} <JWT>'".format(
                header_name, expected_header)
            raise InvalidHeaderError(msg)
        token = parts[1]

    secret = _get_secret_key()
    algorithm = get_algorithm()
    return _decode_jwt(token, secret, algorithm)
示例#14
0
 def wrapper(*args, **kwargs):
     verify_jwt_in_request()
     claims = get_jwt_claims()
     if claims.get('role') != ROLE_ADMIN:
         raise NoAuthorizationError("User not Autohrized")
     else:
         return func(*args, **kwargs)
示例#15
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
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
    if decoded_token['type'] != request_type:
        raise WrongTokenError('Only {} tokens can access this endpoint'.format(request_type))

    # Check if the custom claims in access tokens are valid
    if request_type == 'access':
        if not verify_token_claims(decoded_token['user_claims']):
            raise UserClaimsVerificationError('user_claims verification failed')

    # If blacklisting is enabled, see if this token has been revoked
    if _token_blacklisted(decoded_token, request_type):
        raise RevokedTokenError('Token has been revoked')

    return decoded_token
示例#17
0
def _decode_jwt_from_headers():
    header_name = config.header_name
    header_type = config.header_type

    # Verify we have the auth header
    jwt_header = request.headers.get(header_name, None)
    if not jwt_header:
        raise NoAuthorizationError("Missing {} Header".format(header_name))

    # Make sure the header is in a valid format that we are expecting, ie
    # <HeaderName>: <HeaderType(optional)> <JWT>
    parts = jwt_header.split()
    if not header_type:
        if len(parts) != 1:
            msg = "Bad {} header. Expected value '<JWT>'".format(header_name)
            raise InvalidHeaderError(msg)
        encoded_token = parts[0]
    else:
        if parts[0] != header_type or len(parts) != 2:
            msg = "Bad {} header. Expected value '{} <JWT>'".format(
                header_name, header_type)
            raise InvalidHeaderError(msg)
        encoded_token = parts[1]

    return decode_token(encoded_token)
示例#18
0
def _decode_jwt_from_cookies(request_type):
    if request_type == 'access':
        cookie_key = config.access_cookie_name
        csrf_header_key = config.access_csrf_header_name
    else:
        cookie_key = config.refresh_cookie_name
        csrf_header_key = config.refresh_csrf_header_name

    encoded_token = request.cookies.get(cookie_key)
    if not encoded_token:
        raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key))

    decoded_token = decode_jwt(encoded_token=encoded_token,
                               secret=config.decode_key,
                               algorithm=config.algorithm,
                               csrf=config.csrf_protect)

    # Verify csrf double submit tokens match if required
    if config.csrf_protect and request.method in config.csrf_request_methods:
        csrf_token_in_token = decoded_token['csrf']
        csrf_token_in_header = request.headers.get(csrf_header_key, None)

        if not csrf_token_in_header:
            raise CSRFError("Missing CSRF token in headers")
        if not safe_str_cmp(csrf_token_in_header, csrf_token_in_token):
            raise CSRFError("CSRF double submit tokens do not match")

    return decoded_token
示例#19
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
    if decoded_token['type'] != request_type:
        raise WrongTokenError(
            'Only {} tokens can access this endpoint'.format(request_type))

    # If blacklisting is enabled, see if this token has been revoked
    if config.blacklist_enabled:
        check_if_token_revoked(decoded_token)

    return decoded_token
示例#20
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
示例#21
0
def _decode_jwt_from_json(request_type):
    if request.content_type != "application/json":
        raise NoAuthorizationError("Invalid content-type. Must be application/json.")

    if request_type == "access":
        token_key = config.json_key
    else:
        token_key = config.refresh_json_key

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

    return decode_token(encoded_token)
示例#22
0
def _decode_jwt_from_json(refresh: bool) -> Tuple[str, str]:
    content_type = request.content_type or ""
    if not content_type.startswith("application/json"):
        raise NoAuthorizationError(
            "Invalid content-type. Must be application/json.")

    if refresh:
        token_key = config.refresh_json_key
    else:
        token_key = config.json_key

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

    return encoded_token, None
示例#23
0
文件: security.py 项目: silky/WALKOFF
def _decode_jwt_from_query_string(param_name):
    # Verify we have the query string
    token = request.args.get(param_name, None)
    if not token:
        raise NoAuthorizationError("Missing {} query param".format(param_name))

    return decode_jwt(encoded_token=token,
                      secret=config.decode_key,
                      algorithm=config.algorithm,
                      csrf=False,
                      identity_claim=config.identity_claim)
示例#24
0
def _decode_jwt_from_cookies(type):
    if type == 'access':
        cookie_key = get_access_cookie_name()
    else:
        cookie_key = get_refresh_cookie_name()

    token = request.cookies.get(cookie_key)
    if not token:
        raise NoAuthorizationError('Missing cookie "{}"'.format(cookie_key))
    secret = _get_secret_key()
    algorithm = get_algorithm()
    token = _decode_jwt(token, secret, algorithm)

    if get_cookie_csrf_protect():
        csrf_header_key = get_csrf_header_name()
        csrf = request.headers.get(csrf_header_key, None)
        if not csrf or not safe_str_cmp(csrf, token['csrf']):
            raise NoAuthorizationError(
                "Missing or invalid csrf double submit header")

    return token
示例#25
0
    def wrapper(*args, **kwargs):
        jwt_data, jwt_header = _decode_jwt_from_request(request_type='access')

        if jwt_data['identity']['role'] != 'user':
            authorized = True
        else:
            authorized = False

        if not authorized:
            raise NoAuthorizationError("You are not admin")

        return view_function(*args, **kwargs)
示例#26
0
        def wrapper(*args, **kwargs):
            jwt_data = _decode_jwt_from_request(request_type='access')

            if ACCESS[jwt_data["identity"][1]] >= ACCESS[urole]:
                isRoleAuthorized = True
            else:
                isRoleAuthorized = False

            if not isRoleAuthorized:
                raise NoAuthorizationError(
                    "You are not authorized user to access the API")

            return apifunction(*args, **kwargs)
示例#27
0
def _decode_jwt_from_headers() -> Tuple[str, str]:
    header_name = config.header_name
    header_type = config.header_type

    # Verify we have the auth header
    auth_header = request.headers.get(header_name, "").strip().strip(",")
    if not auth_header:
        raise NoAuthorizationError(f"Missing {header_name} Header")

    # Make sure the header is in a valid format that we are expecting, ie
    # <HeaderName>: <HeaderType(optional)> <JWT>.
    #
    # Also handle the fact that the header that can be comma delimited, ie
    # <HeaderName>: <field> <value>, <field> <value>, etc...
    if header_type:
        field_values = split(r",\s*", auth_header)
        jwt_headers = [s for s in field_values if s.split()[0] == header_type]
        if len(jwt_headers) != 1:
            msg = (f"Missing '{header_type}' type in '{header_name}' header. "
                   f"Expected '{header_name}: {header_type} <JWT>'")
            raise NoAuthorizationError(msg)

        parts = jwt_headers[0].split()
        if len(parts) != 2:
            msg = (f"Bad {header_name} header. "
                   f"Expected '{header_name}: {header_type} <JWT>'")
            raise InvalidHeaderError(msg)

        encoded_token = parts[1]
    else:
        parts = auth_header.split()
        if len(parts) != 1:
            msg = f"Bad {header_name} header. Expected '{header_name}: <JWT>'"
            raise InvalidHeaderError(msg)

        encoded_token = parts[0]

    return encoded_token, None
示例#28
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]
示例#29
0
def _decode_jwt_from_query_string() -> Tuple[str, str]:
    param_name = config.query_string_name
    prefix = config.query_string_value_prefix

    value = request.args.get(param_name)
    if not value:
        raise NoAuthorizationError(f"Missing '{param_name}' query paramater")

    if not value.startswith(prefix):
        raise InvalidQueryParamError(
            f"Invalid value for query parameter '{param_name}'. "
            f"Expected the value to start with '{prefix}'")

    encoded_token = value[len(prefix):]  # noqa: E203
    return encoded_token, None
示例#30
0
    def wrapper(*args, **kwargs):
        jwt_token = request.json.get('refresh_token', None)
        if not jwt_token:
            raise NoAuthorizationError("Missing refresh token")

        decoded_token = decode_jwt(
            jwt_token, config.decode_key, config.algorithm, csrf=False)

        # Make sure the type of token we received matches the request type we expect
        if decoded_token['type'] != 'refresh':
            raise WrongTokenError('Only refresh tokens can access this endpoint')

        # If blacklisting is enabled, see if this token has been revoked
        #if config.blacklist_enabled:
            #check_if_token_revoked(decoded_token)

        ctx_stack.top.jwt = decoded_token
        _load_user(decoded_token['identity'])
        return fn(*args, **kwargs)