def decrypt(self,token): # converts the token back from string to bytes and then loading it using the JSON serialiser payload = self.serial.loads(token.encode()) time_stamp = payload.get('creation-time') if datetime.now() > datetime.strptime(time_stamp, timeformat) + timedelta(minutes=time_expiry): raise SignatureExpired("Token created more than 60 min ago.") return payload
def validate_token(self, token): info = jwt.decode(token, self._secret_key, algorithm='HS256') # check whether the token is expire or not if time() - info['creation_time'] > self._expires_in: raise SignatureExpired( "The Token has been expired; get a new token") return info['username']
def loads(self, s, salt=None, return_header=False, renew_session_duration=False): payload, header = JSONWebSignatureSerializer.loads(self, s, salt, return_header=True) if 'exp' not in header: raise BadSignature('Missing expiry date', payload=payload) if not (isinstance(header['exp'], number_types) and header['exp'] > 0): raise BadSignature('expiry date is not an IntDate', payload=payload) if header['exp'] < self.now(): raise SignatureExpired('Signature expired', payload=payload, date_signed=self.get_issue_date(header)) elif renew_session_duration: header['iat'] = self.now() - self.expires_in header['exp'] = self.now() if return_header: return payload, header return payload
def validate_token(self, token): info = self.serializer.loads(token.encode()) if time() - info['creation_time'] > self.expires_in: raise SignatureExpired("The Token has been expired; get a new token") return info['username']
def decryptToken(token): #sig checks if the data is valid and not unsafe payload = encrypt.loads(token) create = payload.get('creation-time') if datetime.now() > datetime.strptime( create, "%Y-%m-%d %H:%M:%S.%f") + timedelta(minutes=30): raise SignatureExpired("Token created more than 10 seconds ago") return payload
def verify_auth_token(token: str) -> bool: s = Serializer(app.config['SECRET_KEY']) try: s.loads(token) except SignatureExpired: raise SignatureExpired('Token has expired') # valid token, but expired except BadSignature: raise BadSignature('Invalid token') # invalid token return True
def test_should_redirect_to_forgot_password_with_flash_message_when_token_is_expired( app_, client, mock_login, mocker): mocker.patch('app.main.views.new_password.check_token', side_effect=SignatureExpired('expired')) token = generate_token('*****@*****.**', app_.config['SECRET_KEY'], app_.config['DANGEROUS_SALT']) response = client.get(url_for('.new_password', token=token)) assert response.status_code == 302 assert response.location == url_for('.forgot_password', _external=True)
def test_verify_email_redirects_to_email_sent_if_token_expired( client, mocker, api_user_pending, ): mocker.patch('app.main.views.verify.check_token', side_effect=SignatureExpired('expired')) response = client.get(url_for('main.verify_email', token='notreal')) assert response.status_code == 302 assert response.location == url_for('main.resend_email_verification', _external=True)
def validate_token(self, token): # Get token info by decode the given token try: info = jwt.decode(token, self._secret_key, algorithms='HS256') except (jwt.ExpiredSignatureError, jwt.DecodeError, jwt.InvalidTokenError): raise BadSignature("Invalid Token.") # If token is expired if self.is_token_expired(info): print("expired") raise SignatureExpired('Token expired.') return info
def verify_session_token(token): timer = TimestampSigner(app.config["SECRET_KEY"]) serial = Serializer(app.config["SECRET_KEY"]) global user_dict exp = GAV.time_out_req try: sess_token = timer.unsign(token, max_age=exp) userid = serial.loads(sess_token)["userId"] except Exception as e: raise SignatureExpired("Entered signature Expired") return Employee.query.get(userid)
def test_it_is_invalid_with_expired_token(self, schema, serializer): serializer.loads.side_effect = SignatureExpired("Token has expired") with pytest.raises(colander.Invalid) as exc: schema.deserialize({"user": "******", "password": "******"}) serializer.loads.assert_called_once_with("encoded_token", max_age=72 * 3600, return_timestamp=True) assert "user" in exc.value.asdict() assert "Reset code has expired." in exc.value.asdict()["user"]
def test_verify_payload__recognizes_expired_token(mocker): mocker.patch.object(URLSafeTimedSerializer, 'loads').side_effect = SignatureExpired( 'error occured', date_signed=datetime(2013, 1, 15, 6, 48)) with pytest.raises(EventFactory.BrokenRequest) as e: signature.verify_payload('what.ever', 'personal_secret', 'salt', '*****@*****.**', 24) assert e.value.event == 'PAYLOAD_VERIFIED_AS_EXPIRED'
def get_by_token(cls, token): s = TimedJSONWebSignatureSerializer(current_app.config['SECRET_KEY']) # may raise BadSignature or SignatureExpired data = s.loads(token) user = current_app.user_datastore.find_user(id=data['id']) if not user: raise HTTPError(401, 'Unknow user with id {}'.format(data['id'])) if user.token == token: if datetime.datetime.utcnow() < user.token_expires: return user raise SignatureExpired('bad token') raise BadSignature('bad token')
def validate(self, token): """Validate a token to check if it has expired Param: token -- A jwt HS256 encoded token string Return: decoded information in its original format Exception: SignatureExpiredException """ info = jwt.decode(token, self.secret, algorithm='HS256') if time() - info['time'] > self.expire: raise SignatureExpired("The token has been expired") return info
def test_should_redirect_to_forgot_password_with_flash_message_when_token_is_expired( app_, client, mock_login, mocker): mocker.patch( "app.main.views.new_password.check_token", side_effect=SignatureExpired("expired"), ) token = generate_token("*****@*****.**", app_.config["SECRET_KEY"], app_.config["DANGEROUS_SALT"]) response = client.get( url_for_endpoint_with_token(".new_password", token=token)) assert response.status_code == 302 assert response.location == url_for(".forgot_password", _external=True)
def loads(self, s, salt=None, return_header=False): payload = super(TimedJSONWebSignatureSerializer, self).loads(s, salt, return_header) if not 'exp' in payload: raise BadSignature("Missing ['exp'] expiry date", payload=payload) if not isinstance(payload['exp'], int) and payload['exp'] > 0: raise BadSignature("['exp'] expiry date is not and IntDate", payload=payload) if payload['exp'] < now(): raise SignatureExpired('Signature expired', payload=payload) return super(TimedJSONWebSignatureSerializer, self).loads(s, salt, return_header)
def loads(self, encrypted_session, max_age=None): """ Decrypts and deserializes `encrypted_session`, and returns a dictionary. If `max_age` is provided, and the age of the session is older than `max_age` in seconds, :exc:`SignatureExpired` is raised. """ decoded = urlsafe_b64decode(encrypted_session.encode('utf-8')) decrypted = self.decrypt(decoded) session = self.serializer.loads(decrypted) age = self.get_timestamp() - session[self.timestamp_key] if max_age and age > max_age: raise SignatureExpired( 'Signature expired; age {} > max_age {}'.format(age, max_age), payload=session) del session[self.timestamp_key] return session
def verify_token(token, valid_seconds): """Confirm given token is well formed and no older than valid_seconds :param token: URL token to check :param valid_seconds: number of seconds since token generation defining the valid period. :return: user_id baked into the token :raises SignatureExpired if the token is older than valid_seconds :raises BadSignature if the token can't be parsed or validated """ is_valid, has_expired, user_id = (user_manager.token_manager.verify_token( token, valid_seconds)) if has_expired: raise SignatureExpired("Expired token {}".format(token)) if not is_valid: raise BadSignature("Invalid token {}".format(token)) return user_id
def test_gives_message_if_token_has_expired( app_, client, mock_check_invite_token, mocker, ): check_token = mocker.patch('app.main.views.invites.check_token', side_effect=SignatureExpired('this is too old')) response = client.get( url_for('main.accept_invite', token='a really old token')) raw_html = response.data.decode('utf-8') page = BeautifulSoup(raw_html, 'html.parser') check_token.assert_called_once_with(ANY, ANY, ANY, 3600 * 24 * 2) assert response.status_code == 400 assert 'Your invitation to GOV.UK Notify has expired' in page.find( 'h1').text assert not mock_check_invite_token.called
def test_verify_email_redirects_to_email_sent_if_token_expired( app_, mocker, api_user_pending, mock_check_verify_code): from itsdangerous import SignatureExpired mocker.patch('app.main.views.verify.check_token', side_effect=SignatureExpired('expired')) with app_.test_request_context(): with app_.test_client() as client: with client.session_transaction() as session: session['user_details'] = { 'email_address': api_user_pending.email_address, 'id': api_user_pending.id } response = client.get(url_for('main.verify_email', token='notreal')) assert response.status_code == 302 assert response.location == url_for( 'main.resend_email_verification', _external=True)
def loads(self, s, salt=None, return_header=False): payload, header = JSONWebSignatureSerializer.loads(self, s, salt, return_header=True) # 生成新token new_token = None if 'exp' not in header: raise BadSignature('Missing expiry date', payload=payload) int_date_error = BadHeader('Expiry date is not an IntDate', payload=payload) try: header['exp'] = int(header['exp']) except ValueError: raise int_date_error if header['exp'] < 0: raise int_date_error if header['refresh_exp'] < self.now(): # 超过了刷新时间,抛出异常 if header['exp'] < self.now(): raise SignatureExpired( 'Signature expired', payload=payload, date_signed=self.get_issue_date(header), ) # 还在可刷新时间内,生成新的token else: ser = Serializer(current_app.config['SECRET_KEY'], expires_in=self.expires_in) new_token = ser.dumps(payload) if return_header: return payload, new_token, header return payload, new_token
def loads(self, token, max_age=0, return_timestamp=False): raise SignatureExpired("Token has expired")
def validate(self, token): info = self.serializer.loads(token.encode()) if time() > info['exp']: raise SignatureExpired("Token has expired, get a new token.") return info