从url解密令牌

时间:2017-12-05 21:54:46

标签: python django encryption

我正在尝试通过组合ID和日期来创建一个带有令牌的URL,然后创建一个URL并将其发送到邮件。单击链接时,我应该能够解密并获取值。但是我一直在cryptography.fernet.InvalidToken。我不确定我在这里做错了什么?

令牌生成器类

class ExpiringTokenGenerator(object):
    FERNET_KEY = Fernet.generate_key()
    fernet = Fernet(FERNET_KEY)

    EXPIRATION_DAYS = 1

    def _get_time(self):
        """Returns a string with the current UTC time"""
        return datetime.utcnow().strftime('%Y-%m-%d %H-%M-%S')

    def _parse_time(self, d):
        """Parses a string produced by _get_time and returns a datetime object"""
        return datetime.strptime(d, '%Y-%m-%d %H-%M-%S')

    def generate_token(self, text):
        """Generates an encrypted token"""
        full_text = bytes(str(text) + '|' + self._get_time(), encoding='utf-8')
        token = self.fernet.encrypt(full_text)

        return token

    def get_token_value(self, token):
        """Gets a value from an encrypted token.
        Returns None if the token is invalid or has expired.
        """
        value = self.fernet.decrypt(bytes(token.strip("/"), encoding='utf-8'))
        return value


transaction_activation_token = ExpiringTokenGenerator()

发送电子邮件

    message = render_to_string('transaction_active_email.html', {
        'email':serializer.data['user']['email'],
        'domain':current_site.domain,
        'uid': force_bytes(serializer.data['user']['id']),
        'token': transaction_activation_token.generate_token(serializer.data['user']['id']),
    })

    mail_subject = 'Gennemfør transaktion!'
    to_email = serializer.data['user']['email']
    email = EmailMessage(mail_subject, message, to=[to_email])
    email.send()

查看

def activate_transaction(request, token):
    value = transaction_activation_token.get_token_value(token)
    print(value)
    redirect("/")

回溯

Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/[PCNAME]/Documents/repositories/project/trade/views.py", line 130, in activate_transaction
    value = transaction_activation_token.get_token_value(token)
File "/Users/[PCNAME]/Documents/repositories/project/trade/tokens.py", line 33, in get_token_value
    value = self.fernet.decrypt(urlsafe_base64_encode(bytes(token, encoding='utf-8')))
File "/usr/local/lib/python3.6/site-packages/cryptography/fernet.py", line 85, in decrypt
    raise InvalidToken
cryptography.fernet.InvalidToken

0 个答案:

没有答案