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

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.

主站蜘蛛池模板: 连江县| 合川市| 郑州市| 筠连县| 威远县| 仁化县| 大关县| 天气| 微博| 凤阳县| 伊春市| 林周县| 三亚市| 玉环县| 东海县| 犍为县| 科技| 嘉定区| 永善县| 浮山县| 灵寿县| 河源市| 金溪县| 曲靖市| 新余市| 沐川县| 丰原市| 定陶县| 额尔古纳市| 平远县| 武定县| 武宁县| 翁源县| 饶阳县| 星子县| 宜君县| 湾仔区| 廊坊市| 湘潭市| 莎车县| 托克托县|