Python jwt.ExpiredSignature() Examples

The following are 19 code examples of jwt.ExpiredSignature(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module jwt , or try the search function .
Example #1
Source File: validator.py    From django-cognito-jwt with MIT License 9 votes vote down vote up
def validate(self, token):
        public_key = self._get_public_key(token)
        if not public_key:
            raise TokenError("No key found for this token")

        try:
            jwt_data = jwt.decode(
                token,
                public_key,
                audience=self.audience,
                issuer=self.pool_url,
                algorithms=["RS256"],
            )
        except (jwt.InvalidTokenError, jwt.ExpiredSignature, jwt.DecodeError) as exc:
            raise TokenError(str(exc))
        return jwt_data 
Example #2
Source File: BaseMiddleWare.py    From django-RESTfulAPI with MIT License 6 votes vote down vote up
def process_request(self, request):
        if request.META.get('HTTP_AUTHORIZATION'):
            token = (request.META.get('HTTP_AUTHORIZATION').split(' '))[1]
            try:
                payload = jwt_decode_handler(token)
                user_id =  jwt_get_user_id_from_payload_handler(payload)
                if not user_id:
                    return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
                now_user = User.objects.values('id', 'is_freeze').filter(id=user_id).first()
                if not now_user:
                    return JsonResponse({"message": "用户不存在!" , "errorCode": 2, "data": {}})
                if now_user.get('is_freeze'):
                    return JsonResponse({"message": "账户被冻结!", "errorCode": 2, "data": {}})
            except jwt.ExpiredSignature:
                return JsonResponse({"message": 'Token过期' , "errorCode": 2, "data": {}})
            except jwt.DecodeError:
                return JsonResponse({"message": 'Token不合法' , "errorCode": 2, "data": {}})
            except jwt.InvalidTokenError as e:
                return JsonResponse({"message": "出现了无法预料的view视图错误:%s" % e, "errorCode": 1, "data": {}}) 
Example #3
Source File: jwtAuth.py    From django-RESTfulAPI with MIT License 6 votes vote down vote up
def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        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 = 'Token过期'
            raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
        except jwt.DecodeError:
            msg = 'Token不合法'
            raise exceptions.AuthenticationFailed({"message": msg,"errorCode":1,"data":{}})
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        user = self.authenticate_credentials(payload)
        return user, jwt_value 
Example #4
Source File: azuread_b2c.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def user_data(self, access_token, *args, **kwargs):
        response = kwargs.get('response')

        id_token = response.get('id_token')
        if six.PY2:
            # str() to fix a bug in Python's base64
            # https://stackoverflow.com/a/2230623/161278
            id_token = str(id_token)

        jwt_header_json = base64url_decode(id_token.split('.')[0])
        jwt_header = json.loads(jwt_header_json.decode('ascii'))

        # `kid` is short for key id
        key = self.get_public_key(jwt_header['kid'])

        try:
            return jwt_decode(
                id_token,
                key=key,
                algorithms=jwt_header['alg'],
                audience=self.setting('KEY'),
                leeway=self.setting('JWT_LEEWAY', default=0),
            )
        except (DecodeError, ExpiredSignature) as error:
            raise AuthTokenError(self, error) 
Example #5
Source File: course_activity_planner.py    From course-activity-planner with GNU General Public License v3.0 6 votes vote down vote up
def login_req(f):
    @wraps(f)
    def decorated_func(*args, **kwargs):
        if not request.headers.get('Authorization'):
            return jsonify(message='Please login'), 401
        try:
            payload = _parse_token_from_header(request)
            g.user_id = payload['sub']
            return f(*args, **kwargs)
        except DecodeError:
            return jsonify(message='Your session is invalid'), 401
        except ExpiredSignature:
            return jsonify(message='\
Your session has expired. Please login again.'), 401

    return decorated_func 
Example #6
Source File: authentication.py    From django-rest-framework-jwt with MIT License 6 votes vote down vote up
def authenticate(self, request):
        """
        Returns a two-tuple of `User` and token if a valid signature has been
        supplied using JWT-based authentication.  Otherwise returns `None`.
        """
        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, payload) 
Example #7
Source File: azuread_tenant.py    From Dailyfresh-B2C with Apache License 2.0 6 votes vote down vote up
def user_data(self, access_token, *args, **kwargs):
        response = kwargs.get('response')
        id_token = response.get('id_token')

        # decode the JWT header as JSON dict
        jwt_header = json.loads(
            base64.b64decode(id_token.split('.', 1)[0]).decode()
        )

        # get key id and algorithm
        key_id = jwt_header['kid']
        algorithm = jwt_header['alg']

        try:
            # retrieve certificate for key_id
            certificate = self.get_certificate(key_id)

            return jwt_decode(
                id_token,
                key=certificate.public_key(),
                algorithms=algorithm,
                audience=self.setting('SOCIAL_AUTH_AZUREAD_OAUTH2_KEY')
            )
        except (DecodeError, ExpiredSignature) as error:
            raise AuthTokenError(self, error) 
Example #8
Source File: auth.py    From kytos with MIT License 6 votes vote down vote up
def authenticated(func):
    """Handle tokens from requests."""
    @wraps(func)
    def wrapper(*args, **kwargs):
        """Verify the requires of token."""
        try:
            content = request.headers.get("Authorization")
            if content is None:
                raise AttributeError
            token = content.split("Bearer ")[1]
            jwt.decode(token, key=Auth.get_jwt_secret())
        except (
            AttributeError,
            IndexError,
            jwt.ExpiredSignature,
            jwt.exceptions.DecodeError,
        ) as exc:
            msg = f"Token not sent or expired: {exc}"
            return jsonify({"error": msg}), HTTPStatus.UNAUTHORIZED.value
        return func(*args, **kwargs)

    return wrapper 
Example #9
Source File: mixins.py    From django-jwt-auth with MIT License 5 votes vote down vote up
def authenticate(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
            raise exceptions.AuthenticationFailed()

        if len(auth) == 1:
            msg = 'Invalid Authorization header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = ('Invalid Authorization header. Credentials string '
                   'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            payload = jwt_decode_handler(auth[1])
        except jwt.ExpiredSignature:
            msg = 'Signature has expired.'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = 'Error decoding signature.'
            raise exceptions.AuthenticationFailed(msg)

        user = self.authenticate_credentials(payload)

        return (user, auth[1]) 
Example #10
Source File: __init__.py    From ga4gh-server with Apache License 2.0 5 votes vote down vote up
def _decode_header(auth_header, client_id, client_secret):
    """
    Takes the header and tries to return an active token and decoded
    payload.
    :param auth_header:
    :param client_id:
    :param client_secret:
    :return: (token, profile)
    """
    try:
        token = auth_header.split()[1]
        payload = jwt.decode(
            token,
            client_secret,
            audience=client_id)
    except jwt.ExpiredSignature:
        raise exceptions.NotAuthorizedException(
            'Token has expired, please log in again.')
    # is valid client
    except jwt.InvalidAudienceError:
        message = 'Incorrect audience, expected: {}'.format(
            client_id)
        raise exceptions.NotAuthorizedException(message)
    # is valid token
    except jwt.DecodeError:
        raise exceptions.NotAuthorizedException(
            'Token signature could not be validated.')
    except Exception as e:
        raise exceptions.NotAuthorizedException(
            'Token signature was malformed. {}'.format(e.message))
    return token, payload 
Example #11
Source File: azuread.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def user_data(self, access_token, *args, **kwargs):
        response = kwargs.get('response')
        id_token = response.get('id_token')
        try:
            decoded_id_token = jwt_decode(id_token, verify=False)
        except (DecodeError, ExpiredSignature) as de:
            raise AuthTokenError(self, de)
        return decoded_id_token 
Example #12
Source File: microsoft.py    From Dailyfresh-B2C with Apache License 2.0 5 votes vote down vote up
def user_data(self, access_token, *args, **kwargs):
        """Return user data by querying Microsoft service"""
        try:
            return self.get_json(
                'https://graph.microsoft.com/v1.0/me',
                headers={
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + access_token
                },
                method='GET'
            )
        except (DecodeError, ExpiredSignature) as error:
            raise AuthTokenError(self, error) 
Example #13
Source File: views.py    From impactstory-tng with MIT License 5 votes vote down vote up
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not request.headers.get('Authorization'):
            response = jsonify(message='Missing authorization header')
            print u"in login_required with error, Missing authorization header"
            response.status_code = 401
            return response

        try:
            payload = parse_token(request)
        except DecodeError:
            response = jsonify(message='Token is invalid')
            response.status_code = 401
            print u"in login_required with error, got DecodeError"
            return response
        except ExpiredSignature:
            response = jsonify(message='Token has expired')
            response.status_code = 401
            print u"in login_required with error, got DecodeError"
            return response

        # print u"in login_required. payload: {}: ".format(payload)

        g.my_person = None
        if "id" in payload:
            # this uses the current token format
            g.my_person = Person.query.filter_by(id=payload["id"]).first()
        if not g.my_person and "orcid_id" in payload:
            # fallback because some tokens don't have id?
            g.my_person = Person.query.filter_by(orcid_id=payload["orcid_id"]).first()
        if not g.my_person and "sub" in payload:
            # fallback for old token format
            g.my_person = Person.query.filter_by(orcid_id=payload["sub"]).first()
        if not g.my_person:
            print u"in login_required with error, no known keys in token payload: {}".format(payload)

        # print u"in login_required success, got a person {}".format(g.my_person)
        return f(*args, **kwargs)

    return decorated_function 
Example #14
Source File: backend.py    From django-auth-adfs with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate_access_token(self, access_token):
        for idx, key in enumerate(provider_config.signing_keys):
            try:
                # Explicitly define the verification option.
                # The list below is the default the jwt module uses.
                # Explicit is better then implicit and it protects against
                # changes in the defaults the jwt module uses.
                options = {
                    'verify_signature': True,
                    'verify_exp': True,
                    'verify_nbf': True,
                    'verify_iat': True,
                    'verify_aud': True,
                    'verify_iss': True,
                    'require_exp': False,
                    'require_iat': False,
                    'require_nbf': False
                }
                # Validate token and return claims
                return jwt.decode(
                    access_token,
                    key=key,
                    algorithms=['RS256', 'RS384', 'RS512'],
                    verify=True,
                    audience=settings.AUDIENCE,
                    issuer=provider_config.issuer,
                    options=options,
                )
            except jwt.ExpiredSignature as error:
                logger.info("Signature has expired: %s", error)
                raise PermissionDenied
            except jwt.DecodeError as error:
                # If it's not the last certificate in the list, skip to the next one
                if idx < len(provider_config.signing_keys) - 1:
                    continue
                else:
                    logger.info('Error decoding signature: %s', error)
                    raise PermissionDenied
            except jwt.InvalidTokenError as error:
                logger.info(str(error))
                raise PermissionDenied 
Example #15
Source File: jwt_credentials_manager.py    From bii-server with MIT License 5 votes vote down vote up
def get_user(self, token):
        """Gets the user from credentials object. None if no credentials.
        Can raise jwt.ExpiredSignature and jwt.DecodeError"""
        profile = self.get_profile(token)
        if not profile:
            return None
        username = profile.get("user", None)
        user = self.server_store.read_user(username)
        # Timestamp must match with the stored in user, if not,
        # this token is not valid (password has been changed)
        password_timestamp = profile["password_timestamp"]
        if password_timestamp != user.password_timestamp:
            logger.debug("Timestamp doesn't match!")
            raise jwt.DecodeError("Timestamp doesn't match!")
        return username 
Example #16
Source File: jwt_manager.py    From bii-server with MIT License 5 votes vote down vote up
def get_profile(self, token):
        """Gets the user from credentials object. None if no credentials.
        Can raise jwt.ExpiredSignature and jwt.DecodeError"""
        profile = jwt.decode(token, self.secret)
        return profile 
Example #17
Source File: serializers.py    From django-rest-framework-jwt with MIT License 5 votes vote down vote up
def _check_payload(self, token):
        # Check payload valid (based off of JSONWebTokenAuthentication,
        # may want to refactor)
        try:
            payload = jwt_decode_handler(token)
        except jwt.ExpiredSignature:
            msg = _('Signature has expired.')
            raise serializers.ValidationError(msg)
        except jwt.DecodeError:
            msg = _('Error decoding signature.')
            raise serializers.ValidationError(msg)

        return payload 
Example #18
Source File: utils.py    From django-graphql-jwt with MIT License 5 votes vote down vote up
def get_payload(token, context=None):
    try:
        payload = jwt_settings.JWT_DECODE_HANDLER(token, context)
    except jwt.ExpiredSignature:
        raise exceptions.JSONWebTokenExpired()
    except jwt.DecodeError:
        raise exceptions.JSONWebTokenError(_('Error decoding signature'))
    except jwt.InvalidTokenError:
        raise exceptions.JSONWebTokenError(_('Invalid token'))
    return payload 
Example #19
Source File: __init__.py    From lux with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_csrf_token(self, request, token):
        bad_token = request.config['CSRF_BAD_TOKEN_MESSAGE']
        expired_token = request.config['CSRF_EXPIRED_TOKEN_MESSAGE']
        if not token:
            raise PermissionDenied(bad_token)
        try:
            jwt.decode(token, request.cache.session.id)
        except jwt.ExpiredSignature:
            raise PermissionDenied(expired_token)
        except Exception:
            raise PermissionDenied(bad_token)