React如何防止XSS攻击

200 阅读1分钟
  1. Xss: 跨站脚本攻击(Cross-site scripting,XSS)是一种安全漏洞,攻击者可以利用这种漏洞在网站上注入恶意的客户端代码。 若受害者运行这些恶意代码,攻击者就可以突破网站的访问限制并冒充受害者
  2. react 防御Xss

dangerouslySetInnerHTML  // 将html渲染出来

function createMarkup() {
  return {__html: 'First · Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

interweave: interweave.dev

  •   yarn add interweave react;
      
      
      import { Interweave } from 'interweave';
      
      <Interweave content="This string contains <b>HTML</b> and will safely be rendered!" />;
      
      <Interweave
          content="This contains a URL, https://github.com/milesj/interweave, and a hashtag, #interweave, that will be converted to an anchor link!"
          matchers={[new UrlMatcher('url'), new HashtagMatcher('hashtag')]}
      />;
    
  • dompurify

    github.com/cure53/DOMP…

    const createDOMPurify = require('dompurify'); const DOMPurify = createDOMPurify(window); export const domPurify = (domStr: string | Node) => DOMPurify.sanitize(domStr)?.replace(/href/g, 'target='_blank' href');

    import { domPurify } from '@/utils/dompurify'; import React from 'react'; import styles from './index.css'; export const Description: React.FC<{ desc: string[] | string; useHtml?: boolean;}> = (props) => { if (!props.desc) { return null; } const renderDesc = (content: string, i?: number) => <div className={styles.desc} style={{ whiteSpace: 'nowrap' }} dangerouslySetInnerHTML={{ __html: domPurify(content) }} key={i} />; return Array.isArray(props.desc) ? ( <> {props.desc.map((p, i) => renderDesc(p, i))} </> ) : renderDesc(props.desc);};