当前位置: 首页>>代码示例>>Python>>正文


Python jwt.InvalidTokenError方法代码示例

本文整理汇总了Python中jwt.InvalidTokenError方法的典型用法代码示例。如果您正苦于以下问题:Python jwt.InvalidTokenError方法的具体用法?Python jwt.InvalidTokenError怎么用?Python jwt.InvalidTokenError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在jwt的用法示例。


在下文中一共展示了jwt.InvalidTokenError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: decode_jwt

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def decode_jwt(jwt_value):
    """
    :type jwt_value: str
    """
    try:
        headers_enc, payload_enc, verify_signature = jwt_value.split(".")
    except ValueError:
        raise jwt.InvalidTokenError()

    payload_enc += '=' * (-len(payload_enc) % 4)  # add padding
    payload = json.loads(base64.b64decode(payload_enc).decode("utf-8"))

    algorithms = getattr(settings, 'JWT_JWS_ALGORITHMS', ['HS256', 'RS256'])
    public_key_name = 'JWT_PUBLIC_KEY_{}'.format(payload['iss'].upper())
    public_key = getattr(settings, public_key_name, None)
    if not public_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
                                   public_key_name))

    decoded = jwt.decode(jwt_value, public_key, algorithms=algorithms)
    return decoded 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:23,代码来源:utils.py

示例2: authenticate

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [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 InvalidTokenError [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 InvalidTokenError [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

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def decode(self, token) -> Optional[JWTUser]:
        try:
            payload = PyJWT.decode(token, self.secret, algorithms=self.algorithms, **self.options)
            if payload == {}:
                return None
        except PyJWT.MissingRequiredClaimError as exc:
            log.warning('JWT Missing claim: %s', exc.claim)
            return None
        except PyJWT.InvalidTokenError as exc:
            log.exception('JWT Invalid Token: %s', exc.__class__.__name__)
            return None
        except Exception as exc:
            log.exception('JWT Exception: %s', exc.__class__.__name__)
            return None
        _id = payload.get(self.ID)
        username = payload.get(self.USERNAME)
        return JWTUser(id=_id, username=username, token=payload) 
开发者ID:audiolion,项目名称:apistar-jwt,代码行数:19,代码来源:token.py

示例6: decode_auth_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [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

示例7: _jwt_required

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def _jwt_required(realm):
    """Does the actual work of verifying the JWT data in the current request.
    This is done automatically for you by `jwt_required()` but you could call it manually.
    Doing so would be useful in the context of optional JWT access in your APIs.

    :param realm: an optional realm
    """
    token = _jwt.request_callback()

    if token is None:
        raise JWTError('Authorization Required', 'Request does not contain an access token',
                       headers={'WWW-Authenticate': 'JWT realm="%s"' % realm})

    try:
        payload = _jwt.jwt_decode_callback(token)
    except jwt.InvalidTokenError as e:
        raise JWTError('Invalid token', str(e))

    _request_ctx_stack.top.current_identity = identity = _jwt.identity_callback(payload)

    if identity is None:
        raise JWTError('Invalid JWT', 'User does not exist') 
开发者ID:mattupstate,项目名称:flask-jwt,代码行数:24,代码来源:__init__.py

示例8: log_into_subdomain

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def log_into_subdomain(request: HttpRequest, token: str) -> HttpResponse:
    """Given a valid authentication token (generated by
    redirect_and_log_into_subdomain called on auth.zulip.example.com),
    call login_or_register_remote_user, passing all the authentication
    result data that has been stored in redis, associated with this token.
    """
    if not has_api_key_format(token):  # The tokens are intended to have the same format as API keys.
        logging.warning("log_into_subdomain: Malformed token given: %s", token)
        return HttpResponse(status=400)

    try:
        result = ExternalAuthResult(login_token=token)
    except ExternalAuthResult.InvalidTokenError:
        logging.warning("log_into_subdomain: Invalid token given: %s", token)
        return render(request, 'zerver/log_into_subdomain_token_invalid.html', status=400)

    subdomain = get_subdomain(request)
    if result.data_dict['subdomain'] != subdomain:
        raise JsonableError(_("Invalid subdomain"))

    return login_or_register_remote_user(request, result) 
开发者ID:zulip,项目名称:zulip,代码行数:23,代码来源:auth.py

示例9: process_request

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
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": {}}) 
开发者ID:aeasringnar,项目名称:django-RESTfulAPI,代码行数:21,代码来源:BaseMiddleWare.py

示例10: authenticate

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [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 = 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 
开发者ID:aeasringnar,项目名称:django-RESTfulAPI,代码行数:24,代码来源:jwtAuth.py

示例11: is_enabled

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def is_enabled(self):
        """
        Check if two-factor authentication is enabled.

        Returns:
            bool: True if enabled. Otherwise False.

        Examples:
            >>> balena.twofactor_auth.is_enabled()
            False

        """

        try:
            token = self.settings.get(TOKEN_KEY)
            token_data = jwt.decode(token, verify=False)
            if 'twoFactorRequired' in token_data:
                return True
            return False
        except jwt.InvalidTokenError:
            # in case it's not Auth token
            raise exceptions.UnsupportedFeature() 
开发者ID:balena-io,项目名称:balena-sdk-python,代码行数:24,代码来源:twofactor_auth.py

示例12: _decode_jwt_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def _decode_jwt_token(self, req):

        # Decodes the jwt token into a payload
        auth_header = req.get_header('Authorization')
        token = self.parse_auth_token_from_request(auth_header=auth_header)

        options = dict(('verify_' + claim, True) for claim in self.verify_claims)

        options.update(
            dict(('require_' + claim, True) for claim in self.required_claims)
        )

        try:
            payload = jwt.decode(jwt=token, key=self.secret_key,
                                 options=options,
                                 algorithms=[self.algorithm],
                                 issuer=self.issuer,
                                 audience=self.audience,
                                 leeway=self.leeway)
        except jwt.InvalidTokenError as ex:
            raise falcon.HTTPUnauthorized(
                description=str(ex))

        return payload 
开发者ID:loanzen,项目名称:falcon-auth,代码行数:26,代码来源:backends.py

示例13: is_token_blacklisted

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [as 别名]
def is_token_blacklisted(encoded_token, public_key=None):
    """
    Decode an encoded token and check if it is blacklisted.

    Args:
        encoded_token (str): JWT to check
        public key (Optional[str]): key to decode JWT with

    Return:
        bool: whether JWT is blacklisted
    """
    public_key = public_key or keys.default_public_key()
    try:
        token = jwt.decode(
            encoded_token, public_key, algorithm="RS256", audience="openid"
        )
    except jwt.exceptions.InvalidTokenError as e:
        raise JWTError("could not decode token to check blacklisting: {}".format(e))
    return is_blacklisted(token["jti"]) 
开发者ID:uc-cdis,项目名称:fence,代码行数:21,代码来源:blacklist.py

示例14: decode_auth_token

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [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

示例15: authenticate

# 需要导入模块: import jwt [as 别名]
# 或者: from jwt import InvalidTokenError [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 = 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) 
开发者ID:jpadilla,项目名称:django-rest-framework-jwt,代码行数:25,代码来源:authentication.py


注:本文中的jwt.InvalidTokenError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。