首先我应该说我已经阅读了this ,这不是我需要的。我想要我用 html/css 制作的表格,而不是 django 表格。
而我的方法是基于this ,这实际上是在 PHP 中。
我编写了代码,它运行良好,但我相信应该有更好的方法来完成它。
代码的总结是我提交我的表单,将数据和 google recaptcha token 发布到我的函数,然后对其进行一些处理,然后根据处理结果重定向到相关页面,我返回 url和状态再次发送到 jQuery,并使用 jQuery 重定向到该页面。
这是我的代码:
登录.html:
<script src="https://www.google.com/recaptcha/api.js?render=here is recaptcha public key"></script>
<!-- login form and etc -->
<script>
$('#loginForm').submit(function() {
// stop what loginform is going to do
event.preventDefault();
var username = $('#username').val();
var password = $("#password").val();
grecaptcha.ready(function () {
grecaptcha.execute("here is recaptcha public key",
{action: "{% url 'basic_app:login_page' %}"}).then(function (token_id)
{$('#loginForm').prepend('<input type="hidden" name="g-recaptcha-response" value="' + token_id + '">');
$.post("{% url 'basic_app:login' %}", // url
{username: username,password: password,
token_id: token_id,csrfmiddlewaretoken: '{{ csrf_token }}'},
function( result ){
console.log(result);
if(result.status == 0) {
window.location.replace(result.url)
} else if (result.status == 1){
window.location.replace(result.url)
}
},
'json');
});
});
});
views.py:
def user_login(request):
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
token_id = request.POST.get('token_id')
if(token_id):
secretKey = "here is recaptcha secret key"
data = {
'secret': secretKey,
'response': token
}
r = requests.post('https://www.google.com/recaptcha/api/siteverify', data=data)
result = r.json()
....
## some codes for more security
....
response = {'status': 0, 'message':"", 'url': '/'}
return HttpResponse(json.dumps(response), content_type='application/json')
else:
response = {'status': 0, 'message':"", 'url': '/login_page'}
return HttpResponse(json.dumps(response), content_type='application/json')
....
这个方法有没有安全问题?
有没有办法编写更好的代码来使用 recaptcha V3?
谢谢。
最佳答案
更好的步骤:
- 当用户点击提交时,防止默认行为
- 在 onSubmit 中,执行 g-recaptcha 并将 token 存储在表单中
- 像下面的教程一样调用 this.submit() 或 form.submit()
- 在您的 View 中验证验证码。
关于python - 在 django 中使用 google recaptcha V3 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976292/