简体   繁体   中英

How do I prevent url query tampering using flask request.args.get?

I have a url http://localhost:8000/savings?sv=30

In Flask I retrieve the value using Jinja templates to display the value of sv on the screen:

{% set sv = request.args.get('sv', '') %}

<p>{{ sv }}</p>

Is it possible to prevent a user from editing the url to display a different value?

For anyone else wondering I have decided to use encode/decode to obscure the value of sv from users.

I have taken Martijn Pieter's advice to obscure the value as opposed to encrypting the value: Simple way to encode a string according to a password?

import zlib
from base64 import urlsafe_b64encode as b64e, urlsafe_b64decode as b64d

def obscure(data: bytes) -> bytes:
    return b64e(zlib.compress(data, 9))

def unobscure(obscured: bytes) -> bytes:
    return zlib.decompress(b64d(obscured))

where this link is sent to a user:

        link = 'https://localhost:8000/savings?sv=' + bytes.decode(obscure(str.encode(amount)))

Which is then decoded when they click the link:

@onboard.route('/savings', methods=['GET', 'POST'])
def savings():
    savings = request.args.get('sv')
    savings = str.encode(savings)
    savings = unobscure(savings)
    savings = bytes.decode(savings)
    return render_template('onboard/savings.html', savings=savings)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM