def decode_token(token): try: return token except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError() except jwt.InvalidTokenError: raise jwt.InvalidTokenError()
def decode_jwt(self, token: bytes): """Returns a decoded JWT's payload""" key = os.getenv("JWT_SECRET") try: decoded = jwt.decode( token, key, algorithms="HS256", issuer=AuthSettings.JWT_ISSUER, options={"require": ["exp", "iss", "email"]}, ) except jwt.ExpiredSignatureError: self._logger.log( LogEntry(LogLevel.INFO, __name__, "JWT Token expired for user.")) raise jwt.ExpiredSignatureError("Expired token.") except jwt.InvalidIssuerError: self._logger.log( LogEntry(LogLevel.ERROR, __name__, "Attempted to decode token with invalid issuer.")) raise jwt.InvalidIssuerError("Invalid JWT Issuer.") except jwt.InvalidTokenError: self._logger.log( LogEntry(LogLevel.ERROR, __name__, "JWT decoding error when trying to decode token.")) raise jwt.InvalidTokenError("Invalid token.") return decoded
def decode_auth_token(auth_token): """验证Token""" try: # 取消过期时间验证 payload = jwt.decode(auth_token, config.SECRET_KEY, options={'verify_exp': False}) if 'id' in payload['data']: return payload else: raise jwt.InvalidTokenError except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError(ErrorCode.login_error, ErrorMessage.login_error) except jwt.InvalidTokenError: raise jwt.ExpiredSignatureError(ErrorCode.login_error, ErrorMessage.login_error)
def refresh(self, token): validated = self.validate(token) if validated is not None: payload = { "username": validated["username"], "pk": validated["pk"] } return self.create(**payload) raise jwt.ExpiredSignatureError("Signature has expired")
def decode_token(token): try: if Users.check_not_blacklisted(token): payload = jwt.decode(token, app.config['SECRET_KEY']) return payload['sub'] else: raise ValueError('Invalid token') except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError() except jwt.InvalidTokenError: raise jwt.InvalidTokenError()
def test_bad_request(self): api = apis.UserApi() request = messages.SignUpRequest(**self.good_data) response = api.sign_up(request) self.assertIsNotNone(response.access_token) self.assertIsNotNone(response.refresh_token) self.assertIsNotNone(response.id) user_id = response.id access_token = response.access_token refresh_token = response.refresh_token payload = jwt.decode(access_token, JWT_SECRET, JWT_ALGORITHM) self.assertEqual(user_id, int(payload['user_id'])) payload = jwt.decode(refresh_token, JWT_SECRET, JWT_ALGORITHM) self.assertEqual(user_id, int(payload['user_id'])) invalid_data = copy.deepcopy(self.refresh) payload = { 'user_id': int(user_id), 'iss': 'refresh', 'exp': datetime.utcnow() + timedelta(REFRESH_JWT_EXP_DELTA_SECONDS) } refresh_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) invalid_data['refresh_token'] = refresh_token with patch('jwt.decode') as jwt_decode: jwt_decode.side_effect = jwt.ExpiredSignatureError() request = messages.RefreshRequest(**invalid_data) self.assertRaises(endpoints.BadRequestException, api.refresh, request) invalid_data = copy.deepcopy(self.refresh) payload = { 'user_id': int(user_id), 'iss': 'auth', 'exp': datetime.utcnow() + timedelta(REFRESH_JWT_EXP_DELTA_SECONDS) } refresh_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) invalid_data['refresh_token'] = refresh_token request = messages.RefreshRequest(**invalid_data) self.assertRaises(endpoints.BadRequestException, api.refresh, request) invalid_data = copy.deepcopy(self.refresh) payload = { 'user_id': int(user_id), 'iss': 'refresh', 'exp': datetime.utcnow() + timedelta(REFRESH_JWT_EXP_DELTA_SECONDS) } refresh_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM) invalid_data['refresh_token'] = refresh_token request = messages.RefreshRequest(**invalid_data) self.assertRaises(endpoints.BadRequestException, api.refresh, request)
def decode_auth_token(auth_token): if not auth_token or len(auth_token) == 0: raise Exception("auth_token is empty") try: payload = jwt.decode(auth_token, SECRET) return payload['sub'] except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError('Signature expired') return 'Signature expired. Please log in again.' except jwt.InvalidTokenError: raise jwt.InvalidTokenError('Invalid token') return 'Invalid token. Please log in again.'
def decode(self, tokenStr): """Verify JWT""" try: payload = jwt.decode(tokenStr, self.key, algorithms=['HS256']) except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError('Verification token has expired.') except jwt.PyJWTError: raise jwt.PyJWTError('Invalid token') if payload['token_type'] != 'email_confirmation': raise jwt.PyJWTError('Invalid token') return payload
def decode_auth_token(auth_token): """ Decodes the auth token :param auth_token: :return: integer|string """ try: payload = jwt.decode(auth_token, config.get('secret_key')) return payload['sub'] except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError( 'Signature expired. Please log in again.') except jwt.InvalidTokenError: raise jwt.InvalidTokenError('Invalid token. Please log in again.')
def test_deny_authorization_link(self, fake_get_token_from_header, fake_requests): """The `deny` decorator auto sets the Link header for Unauthorized""" fake_get_token_from_header.side_effect = jwt.ExpiredSignatureError( 'TESTING') @http_auth.deny() def fake_func(*args, **kwargs): return True resp = fake_func() found = resp.headers['Link'] expected = '<https://localhost/api/1/auth>; rel=authorization' self.assertEqual(found, expected)
def test_deny_expired_token(self, fake_get_token_from_header, fake_requests): """The `deny` bails early if the token is already expired""" fake_get_token_from_header.side_effect = jwt.ExpiredSignatureError( 'TESTING') @http_auth.deny() def fake_func(*args, **kwargs): return True resp = fake_func() output = (ujson.loads(resp.get_data()), resp.status_code) expected = ({"error": "No Valid Session Found"}, 401) self.assertEqual(output, expected)
def decode_auth_token(auth_token: str) -> int: """Decode authentication token. :param auth_token: Token string :return: Token owner user id """ try: payload = jwt.decode(auth_token, current_app.config['SECRET_KEY'], algorithms=['HS256']) return payload['sub'] # type: ignore except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError( 'Signature expired. Please log in again.') except jwt.InvalidTokenError: raise jwt.InvalidTokenError('Invalid token. Please log in again.')
def myDecode(token, secret): payloadValided = False try: payloadValided = jwt.decode(token, secret, algorithms=['HS256', 'HS512'], verify=False) except jwt.ExpiredSignatureError: raise jwt.ExpiredSignatureError( 'You take too much time for getting your token.', 'You need to login again') except jwt.InvalidTokenError: raise jwt.InvalidTokenError('Exception when decode()') except jwt.DecodeError: raise jwt.DecodeError('We canno\'t decode your token') except jwt.InvalidSignatureError: raise jwt.InvalidSignatureError( 'Your token’s signature doesn’t match' ' the one provided as part of the token') return payloadValided
def decode_token(token): decode_result = {'data': {}, 'error': {}} try: payload = jwt.decode(token, os.getenv('FLASK_APP_JWT_SECRET_KEY')) uid = payload['sub'] # If decode succeeded, token is valid decode_result['data'] = {'user_id': payload['sub']} # Checking revoked users if Auth.is_user_access_revoked(uid, payload['iat_ticks']): raise jwt.ExpiredSignatureError('token revoked') else: return decode_result except jwt.ExpiredSignatureError: decode_result['error'] = {'message': 'token expired'} return decode_result except jwt.InvalidTokenError: decode_result['error'] = {'message': 'invalid token'} return decode_result except Exception: decode_result['error'] = {'message': 'internal error'} return decode_result
def get_expired_token_exception(token): raise jwt.ExpiredSignatureError()