veenaMSL
veenaMSL

Reputation: 111

How to add security headers in loopback4 web application?

I want to add the following security headers in my loopback4 application.

How to do this. I have tried this logic in my application.ts file. But the middleware logic is not working as expected.

const headersMiddleware: Middleware = async (ctx: MiddlewareContext, next) => {
    console.log("Adding security headers...");
    const { response } = ctx;
    console.log("Request URL:", ctx.request.url);

    response.header("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
    response.header("X-Frame-Options", "DENY");
    response.header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';");
    response.header("Referrer-Policy", "strict-origin-when-cross-origin");

    console.log("Security headers added:");
    console.log("Strict-Transport-Security:", response.getHeader("Strict-Transport-Security"));
    console.log("X-Frame-Options:", response.getHeader("X-Frame-Options"));

    return next();
};

console.log("Registering custom headers middleware...");
this.middleware(headersMiddleware);
console.log("Custom headers middleware registered.");

Upvotes: 0

Views: 13

Answers (0)

Related Questions