Reprint big front-end technology road welcome attention
10 React Security Best Practices
Looking for the best way to protect the React application? Then you’ve come to the right place!
I created this List of React security best practices to help you and your team find and resolve security issues in React applications. I show you how to automatically test your React code for security-related issues and fix them.
Let’s get started.
- Default XSS protection for Data Binding
- Dangerous URL
- Rendering HTML
- Direct access to dom
- Server side rendering
- Detect vulnerabilities in dependencies
- JSON State
- Detect the React vulnerable version
- Linter tools
- Dangerous library code
Default XSS protection for Data Binding
Use the default {} for data binding. React automatically escapes values to prevent XSS attacks. Note that this protection only works when rendering textContent, not HTML Attributes.
Use data binding syntax {} to place data in components.
To do this:
<div>{data}</div>
Copy the code
Avoid dynamic HTML Attributes values without custom validation.
Don’t do this:
<form action={data}>.Copy the code
Dangerous URL
Urls can be used to introduce dynamic scripting via javascript: protocol. Verify that your connection is HTTP: or HTTPS: to prevent script injection of javascript: URLS. Use the native URL parsing method to verify the URL to determine if the protocol is on your whitelist.
To do this:
function validateURL(url) {
const parsed = new URL(url)
return ['https:'.'http:'].includes(parsed.protocol)
}
<a href={validateURL(url) ? url : ' '}>Click here! </a>Copy the code
Don’t do this:
<a href={attackerControlled}>Click here!</a>
Copy the code
Rendering HTML
React renders HTML code directly into a DOM node using dangerouslySetInnerHTML. But any content inserted in this way must be sterilized beforehand.
Before putting any value into the dangerouslySetInnerHTML attribute, it needs to be sanitized with DomPurify.
Dompurify is used when inserting HTML
import purify from "dompurify";
<div dangerouslySetInnerHTML={{ __html:purify.sanitize(data) }} />
Copy the code
Direct access to dom
You should avoid accessing the DOM and then injecting content directly into the DOM node. If you must insert HTML, sanitise it with DomPurify first, then use the dangerouslySetInnerHTML attribute.
To do this:
import purify from "dompurify";
<div dangerouslySetInnerHTML={{__html:purify.sanitize(data)}} / >
Copy the code
Do not use refs and findDomNode() to access rendered DOM elements and then inject content with methods or attributes similar to innerHTML.
Don’t do this:
this.myRef.current.innerHTML = attackerControlledValue;
Copy the code
Server side rendering
In the use of like ReactDOMServer. RenderToString () and ReactDOMServer renderToStaticMarkup () this kind of method, data binding will automatically provide content escape function.
Avoid linking some other (unverified) string to the output of renderToStaticMarkup() before sending the string to the client browser for hydration.
Do not connect unsanitized data torenderToStaticMarkup()
On the output to prevent XSS
app.get("/".function (req, res) {
return res.send(
ReactDOMServer.renderToStaticMarkup(
React.createElement("h1".null."Hello World!")
) + otherData
);
});
Copy the code
Detect vulnerabilities in dependencies
Some versions of some third-party components may contain security issues. Check your dependencies and update to a better version.
Use tools similar to Snyk CLI for vulnerability checking.
Snyk CLI can also be integrated with code management systems and then automatically fix bugs:
$ npx snyk test
JSON state
It is common practice to send JSON data along with the React page after SSR. Be sure to transfer < characters with harmless equivalents.
Escape valid HTML values in JSON using benign equivalent characters:
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace( /</g.'\\u003c')}
Copy the code
Vulnerable React version
The React library has had some serious bugs in the past, so it’s best to keep it up to date.
Use NPM outdated to check if you are in the latest version, thus avoiding vulnerable versions of React and the React DOM.
Linter tools
Install Linter configurations and plug-ins that automatically detect security issues in your code and suggest fixes.
Use ESLint React Security Config to check for security vulnerabilities.
Configure a pre-commit hook that will fail when detecting security-related issues using a library like Husky.
Use Snyk to automatically update the version when it detects security issues with your current version.
Dangerous library code
Library code often does dangerous things, such as inserting HTML directly into the DOM. Check the library code manually or using the Linter tool to detect unsafe uses of the React mechanism.
Avoid libraries that use dangerouslySetInnerHTML, innerHTML, unauthenticated urls, or other insecure modes. Use the Linter tool to check the node_modules directory.