Khắc phục lỗi [ Refused to frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'" ] - Expressjs

1 min read

Refused to frame because an ancestor violates the following Content Security Policy directive: "frame-ancestors 'self'"
 là lỗi xảy ra khi chúng ta dùng middleware helmet. Cụ thể hơn là do option frameguard trong helmet đã chặn các trang khác chạy iframe để nhúng trang web của chúng ta vào.

Theo như tài liệu của framguard, nó chỉ cung cấp cho chúng ta 2 options: 
 - SAMEORIGIN (mặc định): Chỉ cho phép các trang có cùng origin truy cập.
 - DENY : Không cho phép bất cứ trang nào khác truy cập.


Để khắc phục vấn đề này, chúng ta chỉ việc thêm frame-ancestors cho Content-Security-Policy bằng cách thêm một middleware để set lại header.
app.use((req, res, next) => {
  res.setheader("content-security-policy", "frame-ancestors https://expressjs.com")
  next()
})

Ví dụ:

const express = require('express')
const helmet = require('helmet')

const app = express()

const port = 3000

app.use(helmet())

app.use((req, res, next) => {
  res.setheader("content-security-policy", "frame-ancestors https://expressjs.com")
  next()
})

app.get('/', (req, res) => {
  res.send('hello world!')
})

app.listen(port, () => {
  console.log(`example app listening on port ${port}`)
})

Kết quả:


Chúc các bạn thành công.

Bận cà phê, bận chơi.

Bạn có thể thích những bài đăng này

Đăng nhận xét