CSRF
- CSRF stands for Cross Site Request Forgery.
- CSRF is when an attacker steals your identity and sends malicious requests on your behalf.
- Include: send mail in your name, send a message, steal your account, even buy goods, virtual currency transfer……
- Problems: personal privacy leakage and property security.
Prevent CSRF attacks
steps
- When the client requests interface data from the back end, the back end sets the cSRF_Token value in the cookie in the response
- Add a hidden field to the Form with a value also cSRF_Token
- When the user clicks submit, it sends a request to the background with these two values
- The back end receives a request to perform the following events:
- Retrieves cSRF_Token from cookie
- The value of cSRF_Token taken from the form data to hide
- To compare
- If the two values are the same, it indicates that the request is normal. If the value is not obtained or the comparison is different, it indicates that the request is not normal and the next step is not performed
Resolve CSRF attacks in the Flask project
In Flask, flask-WTF extension has a complete SET of CSRF protection architecture, which is very easy for us developers to use
Implement validation in FlaskForm
- Set the secret_key for the application
- The value of cSRF_Token used for encryption generation
“# I can write random string # here”
- Add the following code to the form of the template
[HTML]
Plain text view
Copy the code
?
1
2
3
4
5
6
7
|
< form method = "post" >
{{ form.csrf_token() }}
{{ form.username.label }} {{ form.username }}< br />
{{ form.password.label }} {{ form.password }}< br />
{{ form.password2.label }} {{ form.password2 }}< br />
{{ form.submit }}
</ form >
|
- The rendered front end page is:
file:///F:/%E5%B9%BF%E5%B7%9E%E5%B0%B1%E4%B8%9A3%E6%9C%9F/%E7%AC%AC%E5%9B%9B%E9%98%B6%E6%AE%B5%EF%BC%88flask%E6%A1%86%E6 %9E%B6%EF%BC%89/day02/%E6%95%99%E6%A1%88/assets/flaskwtf_csrftoken.png
After setting, the CSRF_Token in the cookie does not need to be cared about and will be set automatically for us
Used alone
- Set the secret_key for the application
- The value of cSRF_Token used for encryption generation
“# I can write random string # here”
- Import the CSRFProtect class in Flask_wtf.csrf, initialize it, and associate it with app during initialization
[Python]
Plain text view
Copy the code
?
1
2
|
from flask.ext.wtf import CSRFProtect
CSRFProtect(app)
|
- If you have a form in the template, you don’t need to do anything. As before:
[HTML]
Plain text view
Copy the code
?
1
|
< form method = "post" > {{ form.csrf_token }} ... </ form >
|
- But if there is no form in the template, you still need a CSRF token:
[HTML]
Plain text view
Copy the code
?
1
|
< form method = "post" action = "/" > < input type = "hidden" name = "csrf_token" value = "{{ csrf_token() }}" /></ form >
|
For more free technical information: annalin1203