當前位置: 首頁>>代碼示例>>Python>>正文


Python jwt.ExpiredSignatureError方法代碼示例

本文整理匯總了Python中jwt.ExpiredSignatureError方法的典型用法代碼示例。如果您正苦於以下問題:Python jwt.ExpiredSignatureError方法的具體用法?Python jwt.ExpiredSignatureError怎麽用?Python jwt.ExpiredSignatureError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在jwt的用法示例。


在下文中一共展示了jwt.ExpiredSignatureError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_transaction_from_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def get_transaction_from_token(view):
    def decorator(request, token):
        try:
            expired = False
            transaction_uuid = jwt.decode(token,
                                          settings.PAYMENT_METHOD_SECRET)['transaction']
        except jwt.ExpiredSignatureError:
            expired = True
            transaction_uuid = jwt.decode(token, settings.PAYMENT_METHOD_SECRET,
                                          options={'verify_exp': False})['transaction']

        try:
            uuid = UUID(transaction_uuid, version=4)
        except ValueError:
            raise Http404

        Transaction = apps.get_model('silver.Transaction')
        return view(request, get_object_or_404(Transaction, uuid=uuid), expired)
    return decorator 
開發者ID:silverapp,項目名稱:silver,代碼行數:21,代碼來源:decorators.py

示例2: authenticate

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
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 = decode_jwt(jwt_value)
        except jwt.ExpiredSignatureError:
            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()

        self._add_session_details(request, payload)

        user = self.authenticate_credentials(payload)
        return user, JwtToken(payload) 
開發者ID:Humanitec,項目名稱:django-oauth-toolkit-jwt,代碼行數:26,代碼來源:authentication.py

示例3: validate

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def validate(self):
        """Decodes the auth token and performs some preliminary validation."""
        self.is_expired = False
        self.is_valid = True
        self.account_id = None

        if self.jwt is None:
            self.is_expired = True
        else:
            try:
                payload = jwt.decode(self.jwt, self.secret)
                self.account_id = payload['sub']
            except jwt.ExpiredSignatureError:
                self.is_expired = True
            except jwt.InvalidTokenError:
                self.is_valid = False 
開發者ID:MycroftAI,項目名稱:selene-backend,代碼行數:18,代碼來源:auth.py

示例4: decode_auth_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def decode_auth_token(auth_token, token_type='Auth'):
        """
        Validates the auth token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, current_app.config.get(
                'SECRET_KEY'), algorithms='HS256')
            is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
            if is_blacklisted_token:
                return 'Token blacklisted. Please log in again.'
            else:
                return payload

        except jwt.ExpiredSignatureError:
            return '{} Token Signature expired.'.format(token_type)
        except jwt.InvalidTokenError:
            return 'Invalid {} Token.'.format(token_type) 
開發者ID:teamsempo,項目名稱:SempoBlockchain,代碼行數:21,代碼來源:user.py

示例5: decode_auth_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def decode_auth_token(cls, token: str):
        """
        驗證token
        :param token:
        :return:
        """
        key = current_app.config.get('SECRET_KEY', cls.key)

        try:
            # 取消過期時間驗證
            # payload = jwt.decode(auth_token, config.SECRET_KEY, options={'verify_exp': False})
            payload = jwt.decode(token, key=key, )

        except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, jwt.InvalidSignatureError):
            return None
        else:
            return payload 
開發者ID:qzq1111,項目名稱:flask-restful-example,代碼行數:19,代碼來源:auth.py

示例6: decode_auth_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def decode_auth_token(self, auth_token):
        """
         驗證Token
        :param auth_token:
        :return: dict
        """
        try:
            payload = jwt.decode(auth_token, self.token_secret, algorithms=['HS256'],
                                 leeway=datetime.timedelta(seconds=10))
            if 'data' in payload and 'user_id' in payload['data']:
                return payload['data']
            else:
                raise jwt.InvalidTokenError
        except jwt.ExpiredSignatureError:
            return dict(status=-1, msg='Token過期')
        except jwt.InvalidTokenError:
            return dict(status=-2, msg='無效Token') 
開發者ID:ss1917,項目名稱:ops_sdk,代碼行數:19,代碼來源:jwt_token.py

示例7: decode_auth_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def decode_auth_token(auth_token):
        """
        Validates the auth token
        :param auth_token:
        :return: integer|string
        """
        try:
            payload = jwt.decode(auth_token, app.config.get('SECRET_KEY'))
            is_blacklisted_token = BlacklistToken.check_blacklist(auth_token)
            if is_blacklisted_token:
                return 'Token blacklisted. Please log in again.'
            else:
                return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.' 
開發者ID:realpython,項目名稱:flask-jwt-auth,代碼行數:19,代碼來源:models.py

示例8: login_required

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def login_required(method):
    @functools.wraps(method)
    def wrapper(self):
        header = request.headers.get('Authorization')
        _, token = header.split()
        try:
            decoded = jwt.decode(token, app.config['KEY'], algorithms='HS256')
        except jwt.DecodeError:
            abort(400, message='Token is not valid.')
        except jwt.ExpiredSignatureError:
            abort(400, message='Token is expired.')
        email = decoded['email']
        if db.users.find({'email': email}).count() == 0:
            abort(400, message='User is not found.')
        user = db.users.find_one({'email': email})
        return method(self, user)
    return wrapper 
開發者ID:oliverSI,項目名稱:flask-restful-authentication,代碼行數:19,代碼來源:api.py

示例9: _auth_with_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def _auth_with_token():
    auth_headers = request.headers.get('Access-Token', '').strip()
    if not auth_headers:
        return False

    try:
        token = auth_headers
        data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'])
        user = User.query.filter_by(email=data['sub']).first()
        if not user:
            return False

        login_user(user)
        g.user = user
        return True
    except jwt.ExpiredSignatureError:
        return False
    except (jwt.InvalidTokenError, Exception):
        return False 
開發者ID:pycook,項目名稱:cmdb,代碼行數:21,代碼來源:auth.py

示例10: _set_error_handler_callbacks

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def _set_error_handler_callbacks(self, app):
        """
        Sets the error handler callbacks used by this extension
        """
        @app.errorhandler(NoAuthorizationError)
        def handle_no_auth_error(e):
            return self._unauthorized_callback(str(e))

        @app.errorhandler(InvalidHeaderError)
        def handle_invalid_header_error(e):
            return self._invalid_token_callback(str(e))

        @app.errorhandler(jwt.ExpiredSignatureError)
        def handle_expired_error(e):
            return self._expired_token_callback()

        @app.errorhandler(jwt.InvalidTokenError)
        def handle_invalid_token_error(e):
            return self._invalid_token_callback(str(e)) 
開發者ID:vimalloc,項目名稱:flask-jwt-simple,代碼行數:21,代碼來源:jwt_manager.py

示例11: authenticate

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def authenticate(cls, jwt_token):
        """
        Validates if JWT Token still stands True.
        :param jwt_token: JWT Token issued by generate_token method
        :return: A dict containing status and payload on success
        """

        if jwt_token:
            try:
                payload = jwt.decode(jwt_token, cls.app_secret)
            except (jwt.DecodeError, jwt.ExpiredSignatureError) as e:
                cls.token_authenticator_logger.exception(
                    '[JWT Manager]: Authentication failed due to : {}'.format(str(e)))
                return {
                    'status': False,
                    'message': 'Token invalid {}'.format(str(e)),
                    'encode_value': None
                }
            cls.token_authenticator_logger.info('[JWT Manager]: Authentication succeded.')
            return {
                'status': True,
                'message': 'Token valid',
                'encode_value': payload['encode_value']
            } 
開發者ID:PruthviKumarBK,項目名稱:PROTON,代碼行數:26,代碼來源:jwt_manager.py

示例12: test_decode_jwt_expired

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def test_decode_jwt_expired(self):
        payload = self._get_payload()
        now = datetime.utcnow()
        payload['exp'] = now - timedelta(seconds=1)
        payload['iat'] = now
        jwt_value = utils.encode_jwt(payload)
        self.assertRaises(jwt.ExpiredSignatureError, utils.decode_jwt,
                          jwt_value) 
開發者ID:Humanitec,項目名稱:django-oauth-toolkit-jwt,代碼行數:10,代碼來源:test_utils.py

示例13: validate_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def validate_token(self, data):
        """Verify token is valid."""
        try:
            payload = jwt.decode(data, settings.SECRET_KEY, algorithms=['HS256'])
        except jwt.ExpiredSignatureError:
            raise serializers.ValidationError('Verification link has expired.')
        except jwt.PyJWTError:
            raise serializers.ValidationError('Invalid token')
        if payload['type'] != 'email_confirmation':
            raise serializers.ValidationError('Invalid token')

        self.context['payload'] = payload
        return data 
開發者ID:pablotrinidad,項目名稱:cride-platzi,代碼行數:15,代碼來源:users.py

示例14: __check_auth

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def __check_auth(self, view):
        headers = {x[0]: x[1] for x in request.headers}
        if 'Authorization' in headers:
            try:
                token = jwt.decode(
                    headers['Authorization'],
                    get_jwt_key_data()
                )

                if token['auth_system'] != current_app.active_auth_system.name:
                    self.log.error('Token is from another auth_system ({}) than the current one ({})'.format(
                        token['auth_system'],
                        current_app.active_auth_system.name
                    ))

                    return view.make_unauth_response()

                if has_access(session['user'], self.role):
                    return

                self.log.error('User {} attempted to access page {} without permissions'.format(
                    session['user'].username,
                    request.path
                ))
                return view.make_unauth_response()

            except (jwt.DecodeError, jwt.ExpiredSignatureError) as ex:
                session.clear()
                view.log.info('Failed to decode signature or it had expired: {0}'.format(ex))
                return view.make_unauth_response()

        session.clear()
        view.log.info('Failed to detect Authorization header')
        return view.make_unauth_response() 
開發者ID:RiotGames,項目名稱:cloud-inquisitor,代碼行數:36,代碼來源:wrappers.py

示例15: decode_auth_token

# 需要導入模塊: import jwt [as 別名]
# 或者: from jwt import ExpiredSignatureError [as 別名]
def decode_auth_token(auth_token):
        """Decodes the auth token - :param auth_token: - :return: integer|string"""
        try:
            payload = jwt.decode(
                auth_token, current_app.config.get('SECRET_KEY'))
            return payload['sub']
        except jwt.ExpiredSignatureError:
            return 'Signature expired. Please log in again.'
        except jwt.InvalidTokenError:
            return 'Invalid token. Please log in again.' 
開發者ID:testdrivenio,項目名稱:flask-microservices-users,代碼行數:12,代碼來源:models.py


注:本文中的jwt.ExpiredSignatureError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。