Escaping HTML in Rails

后端 未结 5 589
终归单人心
终归单人心 2021-02-01 04:12

What is the recommended way to escape HTML to prevent XSS vulnerabilities in Rails apps?

Should you allow the user to put any text into the database but escape it when d

5条回答
  •  长发绾君心
    2021-02-01 05:07

    The h is an alias for html_escape, which is a utility method for escaping all HTML tag characters:

    html_escape('')
    # => <script src=http://ha.ckers.org/xss.js></script>
    

    If you need more control, go with the sanitize method, which can be used as a white-list of tags and attributes to allow:

    sanitize(@article.body, :tags => %w(table tr td), :attributes => %w(id class style))
    

    I would allow the user to input anything, store it as-is in the database, and escape when displaying it. That way you don't lose any information entered. You can always tweak the escaping logic later...

提交回复
热议问题