Issue
Lots of code I've seen online for login routing in Flask looks like this,
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
password = request.form.get('password')
if password == "pass":
#login
return redirect('/index')
return render_template(login.html)
for
<form action='/login' method='POST'>
<input type='password' id="pass' name='pass'>
<input type='submit' value='Login'>
</form>
However the way I first wrote it was,
@app.route('/login', methods=['GET', 'POST'])
def login():
password = request.form.get('password')
if password == "pass":
#login
return redirect('/index')
return render_template(login.html)
i.e., not first checking the request is a POST. Both work, but from what I've read online, the former is considered more secure - can someone tell me why?
If we had something like
password = request.args.get('password')
Then I can see why not checking the request is a POST could be less secure, because we could login with the URL,
/login?password=pass
Which shows the password in the URL and is easier to brute force. But it is my understanding
request.forms.get('password')
cannot be manipulated through URLs in the same way. So why is checking for POST better/safer?
Solution
You are correct that request.form will never contain any data for a get request and that in your specific example checking that it is a post request is unnecessary and does not improve security. The problem with not checking the request type is that your code cannot otherwise differentiate between the initial get request to display the form in the first place and the user submitting an empty form where you might want to display an error message to help them understand what they need to do. Also when using a form to edit data, checking the request type is necessary to differentiate between the initial data that you supply to the user and their edited data. Seeing as the request type check is necessary in the vast majority of cases it is standard practice to always include it but you can safely omit it in your very specific case.
Answered By - EAW
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.