Create a secure unsubscribe link for emails sent with Flask Create a secure unsubscribe link for emails sent with Flask flask flask

Create a secure unsubscribe link for emails sent with Flask


Flask includes the library itsdangerous which is used to generate tokens by securely signing serialized data.

For each email, generate a token with the email to be unsubscribed, and create an unsubscribe route that accepts and decodes that token to determine who to unsubscribe.

from itsdangerous import URLSafeSerializer, BadData@app.route('/unsubscribe/<token>')def unsubscribe(token):    s = URLSafeSerializer(app.secret_key, salt='unsubscribe')    try:        email = s.loads(token)    except BadData:        # show an error        ...    # unsubscribe    ...def send_email():    s = URLSafeSerializer(app.secret_key, salt='unsubscribe')    token = s.dumps(user.email)    url = url_for('unsubscribe', token=token)    # add the url to your message    ...

Since the token is signed, a user can see the data but can't change it without invalidating the token.