简体   繁体   English

XSS 保护 HTML 实体

[英]XSS Protection HTML Entities

Do you think that this functions are enough to prevent XSS if used to filter user input?如果用于过滤用户输入,您认为这些功能足以防止 XSS 吗? And should I really make my own or use XSS libraries available?我真的应该自己制作或使用 XSS 库吗? Give me constructive criticism please.请给我建设性的批评。 Thank you everyone.谢谢大家。

/**
 * Escape HTML string to prevent XSS.
 */
export const escapeHtml = (string: string): string => {
    if (isString(string)) {
        const entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': "&quot;"
        };
        return string.slice(0, string.length).replace(/[&<>"]/g, (s: string): string => entityMap[s]);
    }
    return string;
};

/**
 * Loop over Object to escape each of its value to prevent XSS.
 */
export const escapeHtmlQueryObject = (obj: { [string]: string }): { [string]: string } => {
    let result = obj;
    if (obj && isObject(obj)) {
        result = Object.keys(obj).reduce((res: { [string]: string }, key: string): {
            [string]: string
        } => {
            res[key] = escapeHtml(obj[key]);
            return res;
        }, {});
    } else if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
        console.error(`FilterXSSQueryObject can't process ${obj.toString()}`);
    }
    return result;
};

Compared to this answer , you may want to escape single quotes also.此答案相比,您可能还想转义单引号。

That said, if you want to make sure your code is secure, it may be better to rely on a library that has been battle tested by security experts.也就是说,如果你想确保你的代码是安全的,最好依赖一个已经过安全专家实战测试的库。

People don't like loading libraries for small things, but this is an important small thing, so I wouldn't mind it.人们不喜欢为小事加载库,但这是一件重要的小事,所以我不介意。

Unrelated: it seems that you're iterating over an object's keys to access its values in a roundabout way using Object.keys , but you can also just use Object.values .不相关:您似乎正在使用Object.keys以迂回的方式遍历对象的键以访问其值,但您也可以只使用Object.values

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

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