Example #1
0
 def wrapper(*args, **kwargs):
     if request.method not in config.exempt_methods:
         jwt_data = _decode_jwt_from_request(request_type='access')
         ctx_stack.top.jwt = jwt_data
         verify_token_claims(jwt_data)
         _load_user(jwt_data[config.identity_claim_key])
     return fn(*args, **kwargs)
Example #2
0
 def wrapper(*args, **kwargs):
     try:
         jwt_data = _decode_jwt_from_request(request_type='access')
         ctx_stack.top.jwt = jwt_data
         verify_token_claims(jwt_data)
         _load_user(jwt_data[config.identity_claim_key])
     except (NoAuthorizationError, InvalidHeaderError):
         pass
     return fn(*args, **kwargs)
Example #3
0
def verify_jwt_in_request():
    """
    Ensure that the requester has a valid access token. This does not check the
    freshness of the access token. Raises an appropiate exception there is
    no token or if the token is invalid.
    """
    if request.method not in config.exempt_methods:
        jwt_data = _decode_jwt_from_request(request_type='access')
        ctx_stack.top.jwt = jwt_data
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
Example #4
0
def token_login(data):
    tokendata = decode_token(data['jwt'])
    try:
        verify_token_claims(tokendata)
    except UserClaimsVerificationError:
        return
    join_room('user' + tokendata['identity'])

    socketio.emit('notification',
                  {'count': misc.get_notification_count(tokendata['identity'])},
                  namespace='/snt',
                  room='user' + tokendata['identity'])
Example #5
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]
Example #6
0
def token_login(data):
    tokendata = decode_token(data["jwt"])
    try:
        verify_token_claims(tokendata)
    except UserClaimsVerificationError:
        return
    join_room("user" + tokendata["identity"])

    socketio.emit(
        "notification",
        {"count": misc.get_notification_count(tokendata["identity"])},
        namespace="/snt",
        room="user" + tokendata["identity"],
    )
Example #7
0
def __verify_token(request_type):
    from flask import request
    from flask_jwt_extended.config import config
    from flask_jwt_extended.view_decorators import _decode_jwt_from_request as decode
    from flask_jwt_extended.utils import verify_token_claims
    try:
        from flask import _app_ctx_stack as ctx_stack
    except ImportError:
        from flask import _request_ctx_stack as ctx_stack

    if request.method not in config.exempt_methods:
        jwt_data = decode(request_type=request_type)
        ctx_stack.top.jwt = jwt_data
        verify_token_claims(jwt_data)
Example #8
0
def custom_verify_jwt_in_request(**options):
    """
    Ensure that the requester has a valid access token. This does not check the
    freshness of the access token. Raises an appropiate exception there is
    no token or if the token is invalid.
    """
    if request.method not in config.exempt_methods:
        jwt_data = decode_jwt_from_request(
            request_type='access',
            allow_expired=options.get("allow_expired", False),
            locations=options.get("locations", []))
        ctx_stack.top.jwt = jwt_data
        verify_token_claims(jwt_data)
        _load_user(jwt_data[config.identity_claim_key])
Example #9
0
 def wrapper(*args, **kwargs):
     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])
     return fn(*args, **kwargs)
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
 def wrapper(*args, **kwargs):
     jwt_data = _decode_jwt_from_request(request_type='access')
     ctx_stack.top.jwt = jwt_data
     if not verify_token_claims(jwt_data[config.user_claims]):
         raise UserClaimsVerificationError(
             'User claims verification failed')
     _load_user(jwt_data[config.identity_claim])
     return fn(*args, **kwargs)
Example #12
0
def verify_fresh_jwt_in_request():
    """
    Ensure that the requester has a valid and fresh access token. Raises an
    appropiate exception if there is no token, the token is invalid, or the
    token is not marked as fresh.
    """
    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])
Example #13
0
def verify_jwt_in_request_optional():
    """
    Optionally check if this request has a valid access token.  If an access
    token in present in the request, :func:`~flask_jwt_extended.get_jwt_identity`
    will return  the identity of the access token. If no access token is
    present in the request, this simply returns, and
    :func:`~flask_jwt_extended.get_jwt_identity` will return `None` instead.

    If there is an invalid access token in the request (expired, tampered with,
    etc), this will still raise the appropiate exception.
    """
    try:
        if request.method not in config.exempt_methods:
            jwt_data = _decode_jwt_from_request(request_type='access')
            ctx_stack.top.jwt = jwt_data
            verify_token_claims(jwt_data)
            _load_user(jwt_data[config.identity_claim_key])
    except (NoAuthorizationError, InvalidHeaderError):
        pass
Example #14
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))
Example #15
0
 def wrapper(*args, **kwargs):
     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')
     if not verify_token_claims(jwt_data[config.user_claims_key]):
         raise UserClaimsVerificationError(
             'User claims verification failed')
     _load_user(jwt_data[config.identity_claim_key])
     return fn(*args, **kwargs)