CSRF
2023. 12. 11. 17:37ㆍFlask
csrf는 cross site request forgery의 약자이며
간단히 설명하면 Server측에서 의도하지 않은 곳에서 요청을 보내거나 의도하지 않은 곳으로 요청을 보내는 공격 방식이다
이중 의도하지 않은 곳에서 요청을 보내는 경우를 방지할 때 Server측에서 보내는 의도적인 난수를 같이 보내게 해
다른 곳에서 보낸 것인지 아니면 적법한 요청이 맞는 지 확인 할 수 있다
보통 이 난수를 csrf token이라 부르며
flask_wtf 라이브러리를 이용하면 간단하게 구현 할 수 있다
from flask_wtf.csrf import CSRFProtect
csrf = CSRFProtect()
csrf.init_app(app)
이 방법을 사용하면 자동으로 html 요청에 csrf token을 같이 보내고
post 요청에서 확인 함으로서 요청이 제대로 온 것인지 아니면 다른 곳에서 온 것인 지 확인한다
<form method = "POST">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
<p>제목 : <input type="text" name = "title" value = "test title"></p>
<p>내용 : <input type="text" name = "content" value = "test content"> </p>
<input type="submit">
</form>
html form에 csrf token을 같이 보내줘야 한다
from flask import Blueprint, render_template, request
form_test = Blueprint("form_test",__name__,url_prefix= '/form')
@form_test.route('/test',methods=('POST','GET',))
def test_form():
if request.method == "POST":
form = request.form
data = form['title']
print(data)
content = form['content']
print(content)
test = {'title':data, 'content':content}
return render_template("post_get_test/form_post.html",form = test)
else:
return render_template("post_get_test/form_get.html")
form을 처리하는 함수는 따로 바꿀 필요가 없다
'Flask' 카테고리의 다른 글
| WebSocket (0) | 2023.12.11 |
|---|---|
| Session login (0) | 2023.12.11 |
| MongoDB (0) | 2023.12.11 |
| Route (0) | 2023.12.11 |
| render_template (0) | 2023.12.10 |