官术网_书友最值得收藏!

Express Helmet

Helmet is a tool that allows you to set various HTTP headers to secure your application.

We can enable the Express.js Helmet middleware as follows in the server index.js file:

app.use(helmet());
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "*.amazonaws.com"]
}
}));
app.use(helmet.referrerPolicy({ policy: 'same-origin' }));

We are doing multiple things here at once. We add some XSS(Cross-Site-Scripting) protection tactics and remove the X-Powered-By HTTP header and some other useful things just by using the helmet() function in the first line.

You can look up the default parameters,  as well as other functionalities of Helmet, at,  https://github.com/helmetjs/helmet. Always be conscious when implementing security features and do your best to verify your attack protection methods.

Furthermore, to ensure that no one can inject malicious code, we are using the Content-Security-Policy HTTP header or, in short, CSP. This header prevents attackers from loading resources from external URLs. 

As you can see, we also specify the imgSrc field, which tells our client that only images from these URLs should be loaded, including Amazon Web Services (AWS). We will see how to upload images to it in Chapter 7Handling Image Uploads, of this book.

Read more about CSP and how it can make your platform more secure at, https://helmetjs.github.io/docs/csp/.

The last enhancement is to set the Referrer HTTP header only when making requests on the same host. When going from domain A to domain B, for example, we do not include the referrer, which is the URL the user is coming from. This enhancement stops any internal routing or requests being exposed to the internet.

It is important to initialize Helmet very high in your Express router so that all responses are affected.

主站蜘蛛池模板: 志丹县| 沙河市| 宜州市| 游戏| 尖扎县| 仲巴县| 桐庐县| 三都| 衡东县| 文山县| 庆云县| 什邡市| 尖扎县| 贺州市| 神木县| 海安县| 白城市| 阿巴嘎旗| 桐乡市| 泰兴市| 溧水县| 额敏县| 龙山县| 韶关市| 渑池县| 泽库县| 定远县| 浦县| 凤山市| 张家口市| 汕尾市| 策勒县| 溧阳市| 荆州市| 班玛县| 东至县| 来宾市| 姚安县| 孙吴县| 炉霍县| 深州市|