【问题标题】:Django how to secure hidden input fields and prevent forms submitting if value changed?如果值更改,Django 如何保护隐藏的输入字段并防止表单提交?
【发布时间】:2021-08-08 19:05:03
【问题描述】:

我在隐藏输入中呈现少量数据。用户可以检查 html 页面并查看那些隐藏的输入数据。他还可以更改隐藏的输入数据,这是我网站的一种安全风险。比如我有一个隐藏的输入,其中用户电子邮件和名称呈现这样的

<input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> 

用户可以检查 html 并更改值,然后我的表单提交新的更新值。如果值更改,有什么方法可以停止提交表单。这是我的代码:

#html模板

{% for i in currentuser_details %}
{%for y in user_profile%}
 <input type="hidden" name='userprofile' value="{{y.id}}">
{%endfor%}        
 <input type="hidden" name="name" class="form-control"  placeholder="Your Name"  value="{{i.first_name}}" required>
<input type="hidden" name="email" class="form-control" placeholder="Enter email"value="{{ i.email }}" required>
 {%endfor%}

#html隐藏的输入渲染数据

    <input type="hidden" name="name" class="form-control" placeholder="Your Name" value="Jhone" required=""> 
 <input type="hidden" name="email" class="form-control" placeholder="Your Name" value="Jhone@gmail.com" required=""> 

   <input type="hidden" name='userprofile' value="1">
        
  <input type="hidden" name="parent" id="parent_id" value="95">

userprofileparent 对我来说最重要的字段。我想防止表单在任何隐藏值发生变化时提交。

froms.py

class CommentFrom(forms.ModelForm):
      captcha = CaptchaField()
      
      class Meta:
          model = BlogComment
          fields = ['name','email','comment','parent','sno','blog','user','userprofile']

views.py

if request.method == "POST":
       if comment_form.is_valid():
                isinstance = comment_form.save(commit=False)
                
                if request.user.is_authenticated:
                   isinstance.user = request.user
                elif not request.user.is_authenticated:
                   User = get_user_model()
                   isinstance.user = User.objects.get(username='anonymous_user')
                
                isinstance.blog = blog
                isinstance.save()
                messages.add_message(request, messages.INFO, 'Your Comment Pending for admin approval')
                return redirect('blog:blog-detail',slug=blog.slug)
       else:
           messages.add_message(request, messages.INFO, "your comment didn't submitted. please submit again ")
                
    else:
          comment_form = CommentFrom()

user_profile 和 currentuser_details 的查询集,它们在视图中使用并将上下文传递给我的 html 页面。

user_profile = UserProfile.objects.filter(user=request.user)

currentuser_details = UserManagement.objects.filter(username=request.user) user_profile = UserProfile.objects.filter(user=request.user)

我认为我需要在 froms.py 或 views.py 中添加验证,但我不知道如何为隐藏的输入和隐藏的外键字段添加验证。

【问题讨论】:

  • 我不知道如果使用检查更改了值,是否可以直接阻止用户提交表单,尤其是在客户端执行此操作。您可能可以在服务器端执行此操作,但我想您可以尝试禁用检查(尽管不建议这样做并且不能完全工作)
  • John Doe 感谢您的评论。我需要在 froms.py 或 views.py 中添加验证,但我不知道。正在寻找适当的答案,希望有人能在这个话题上帮助我。

标签: python django


【解决方案1】:

您可以使用request.session。我的意思是在渲染页面之前,你可以像这样设置值。

request.session['secret_data'] = {"key1": "value1", "key2": "value2"}

然后您可以创建一个验证函数,该函数将对提交的表单数据和request.session['secret_data'] 值运行验证。如果验证结果为真,您可以保存数据,否则可以提出您想要的任何消息。

def validate_hidden_values(request,**kwargs):
    original_data = request.session['secret_data']
    # Used **kwargs because i do not know what all the named variables you want to validate. You can get submitted data from **kwargs
    # run your validation checks
    # return True if all validation passes else return False at any point where validation fails

当验证为True 时,请记住使用request.session.pop('secret_data') 删除secret_data 键。现在,当验证为 False 时删除 secret_data 键取决于您的用例,您必须考虑一下。

【讨论】:

  • Amandeep Singh Sawhney 感谢您的回答。您能否以我的任何字段为例,向我展示如何使用会话进行处理。让我们选择隐藏的名称字段。它可以帮助我理解如何正确实现您的代码。
  • 请考虑一下。添加一些您将如何设置secret_data 的代码。 secret_data 只不过是您想要验证的原始值的字典。阅读有关如何引发自定义异常的信息。此时发布的问题详细信息非常广泛。请尝试缩小范围。
  • Amandeep Singh Sawhney 如何在上下文中传递会话以及如何在我的 html 中呈现它???
  • 上下文中已经有请求对象。在django模板中可以直接访问{{ request.session }}
  • Amandeep Singh Sawhney 在我的隐藏输入中,我正在尝试这个&lt;input type="hidden" name="name" value="{{request.session.key1}}" required&gt;,但没有工作。在我的views.py中我添加了`request.session['secret_data'] = {"key1": name}`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-25
相关资源
最近更新 更多