简体   繁体   English

我想使用markdown来安全地保存数据(对于xss)而不是json.stringify()方法

[英]Node js .I want to use markdown to save the data securely(for xss) instead of json.stringify() method

I want to use markdown to save the data securely instead of json.stringfy() method.Like this exapmle:usercomment is <script>alert('ss')</script> 我想使用markdown而不是json.stringfy()方法安全地保存数据。就像这个例子:用户评论是<script>alert('ss')</script>

 app.get('/comment',function(req.res){ var usercomment=req.body.comment;//from comment textarea(user's comment) const x=markdown.toHTML(usercomment); var comments=new comment({user:req.session.nick,comment:x}); comments.save(); console.log(x) } 

Or use json.stringify() like this I save the usercomment with json.stringify().Later i will send the comment(from database) to html with markdown.toHTML(comment) : 或者像这样使用json.stringify(), 我将用户注释保存为json.stringify()。稍后我将使用markdown.toHTML(comment)将注释(来自数据库)发送到html

 app.get('/comment',function(req.res){ var usercomment=req.body.comment; const x=JSON.stringify(usercomment); var comments=new comment({user:req.session.nick,comment:x}); comments.save(); console.log(x) } 
Which one should I use? 我应该使用哪一个?

JSON and Markdown do not give you security JSON和Markdown不能给您安全

Neither of the things you mention will magically give you security. 您提到的任何事情都不会神奇地为您提供安全性。 To handle dangerous user input, you need to sanitize the input. 要处理危险的用户输入,您需要清理输入。

A quick search on NPM gives me sanitize-html , which seems like it would be good for this purpose. 快速搜索NPM可以得到sanitize-html ,这似乎很适合此目的。

const sanitizeHtml = require('sanitize-html');
app.post('/comment', function(req, res){
    let usercomment = req.body.comment;
    let safe_comment = sanitizeHtml(usercomment);
    let comments = new comment({
        user: req.session.nick,
        comment:safe_comment,
    });
    comments.save();
    res.send('saved');
}

If you don't want to allow your users to use any HTML, you can escape the user comment so that their input does not act like HTML. 如果您不想允许用户使用任何HTML,则可以转义用户注释,以使他们的输入不像HTML。 ( htmlencode seems good for this purpose) htmlencode似乎很好用)

const htmlencode = require('htmlencode');
app.post('/comment', function(req, res){
    let usercomment = req.body.comment;
    let safe_comment = htmlencode.htmlEncode(usercomment);
    let comments = new comment({
        user: req.session.nick,
        comment:safe_comment,
    });
    comments.save();
    res.send('saved');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM