Laravel5 - 如何在Blade中只渲染html标签而不是javascript?

时间:2015-11-05 19:53:31

标签: security laravel laravel-5 xss

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

{!! $content !!}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

Blade中没有任何内容可以做到这一点。它为您提供{!! !!}选项,以便您在必要时进行自己的清洁。如果您希望HTML能够工作,但是阻止了Javascript,那么您需要做一些工作来专门净化它。这是一个在Laravel 5中实现流行HTMLpurifier的软件包:

https://github.com/etcinit/purifier

您可以看到,通过默认配置,它使用白名单来确保javascript无法通过:

的src / Chromabits /净化器/ 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