XSS安全漏洞 防御
2019年4月7日HTMLPurifier for Laravel 5
HTMLPurifier for Laravel 是对 HTMLPurifier 针对 Laravel 框架的一个封装。本章节中,我们将使用此扩展包来对用户内容进行过滤。
1. 安装 HTMLPurifier for Laravel 5
使用 Composer 安装:
1 |
$ composer require "mews/purifier:~2.0" |
2. 配置 HTMLPurifier for Laravel 5
命令行下运行
1 |
$ php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider" |
请将配置信息替换为以下:
config/purifier.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php return [ 'encoding' => 'UTF-8', 'finalize' => true, 'cachePath' => storage_path('app/purifier'), 'cacheFileMode' => 0755, 'settings' => [ 'user_topic_body' => [ 'HTML.Doctype' => 'XHTML 1.0 Transitional', 'HTML.Allowed' => 'div,b,strong,i,em,a[href|title],ul,ol,ol[start],li,p[style],br,span[style],img[width|height|alt|src],*[style|class],pre,hr,code,h2,h3,h4,h5,h6,blockquote,del,table,thead,tbody,tr,th,td', 'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,margin,width,height,font-family,text-decoration,padding-left,color,background-color,text-align', 'AutoFormat.AutoParagraph' => true, 'AutoFormat.RemoveEmpty' => true, ], ], ]; |
3.开始过滤
一切准备就绪,现在我们只需要在数据入库前进行过滤即可:
app/Observers/TopicObserver.php
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php namespace App\Observers; use App\Models\Topic; // creating, created, updating, updated, saving, // saved, deleting, deleted, restoring, restored class TopicObserver { public function saving(Topic $topic) { $topic->body = clean($topic->body, 'user_topic_body'); $topic->excerpt = make_excerpt($topic->body); } } |