【问题标题】:Laravel5 - How to render only html tags not javascript in Blade?Laravel5 - 如何在 Blade 中只呈现 html 标签而不是 javascript?
【发布时间】:2015-11-05 19:53:31
【问题描述】:

我想将用户输入 $content 呈现为 HTML,但阻止 JavaScript 在刀片模板引擎中执行(用于防止 XSS 攻击)。以下代码同时呈现 HTML 和 JavaScript。

{!! $content !!}

我该怎么做?

【问题讨论】:

  • AFAIK,这不是 Blade 内置的。您需要使用strip_tags 来提取<script> 和类似DOMDocument 来解析出onload 等。
  • 看看this answer
  • 您需要构建自己的函数来执行此操作。
  • strip_tags 不应被依赖。他需要 HTMLpurifier 之类的东西。看我的回答。

标签: security laravel laravel-5 xss


【解决方案1】:

Blade 中没有内置任何东西来执行此操作。它为您提供{!! !!} 选项,因此您可以在必要时进行自己的清洁。如果您希望您的 HTML 工作,但阻止 Javascript,那么您将需要做一些工作来专门净化它。这是一个在 Laravel 5 中实现流行的 HTMLpurifier 的包:

https://github.com/etcinit/purifier

您可以看到,在默认配置下,它使用白名单来确保 javascript 不会通过:

src/Chromabits/Purifier/Purifier.php

protected function getDefaultConfig()
{
        return [
            'HTML.Doctype' => 'XHTML 1.0 Strict',
            'HTML.Allowed' => 'div,b,strong,i,em,a[href|title],ul,ol,li'
                . ',p[style],br,span[style],img[width|height|alt|src]',
            'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style'
                . ',font-family,text-decoration,padding-left,color'
                . ',background-color,text-align',
            'AutoFormat.AutoParagraph' => true,
            'AutoFormat.RemoveEmpty' => true,
        ];
}

在你的控制器中使用它:

public function getIndex(Request $request)
{
    return $this->purifier->clean($request->input('first_name'));
}

另一种选择是不允许您的用户直接输入 HTML,而是使用类似 Markdown 的内容。这就是 StackOverFlow does

【讨论】:

  • 看起来可以工作了。但我认为一定有更简单的事情。
  • 更新了我的答案,让你有更多的洞察力。
  • 非常感谢你的程序
  • 您是否考虑过使用 Markdown 代替(就像 Stackoverflow 一样)? github.com/GrahamCampbell/Laravel-Markdown
猜你喜欢
  • 2017-12-06
  • 2020-03-11
  • 1970-01-01
  • 2019-12-09
  • 1970-01-01
  • 2021-12-13
  • 2019-01-09
  • 2019-02-02
  • 2011-07-15
相关资源
最近更新 更多