我發現在嘗試呼叫 REST API 時很難理解我的應用程式拋出的錯誤。
我的應用程式是一個純 HTML、基于 jQuery 的 JavaScript,在 Jetty 服務器中運行。服務器已實作Content-Security-Policy:
Custom HTTP headers to be added to our responses: Content-Security-Policy:
default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; connect-src 'self';
img-src 'self' data:; style-src 'self' 'unsafe-inline'; base-uri 'self';
frame-ancestors 'self'; font-src 'self';frame-src 'self'|X-Frame-Options:
SAMEORIGIN|X-Content-Type-Options: nosniff|X-XSS-Protection: 1; mode=block|
Referrer-Policy: strict-origin|Feature-Policy: 'none'|Strict-Transport-Security:
max-age=63072000; includeSubDomains; preload
我理解這部分。任何試圖訪問我的應用程式的人都必須遵守這些限制。
但是,我的應用程式中的 JavaScript 代碼嘗試呼叫在同一 Linux VM 上運行的 Spring Boot REST API(http://localhost:8080/... 或 http://server-host-name:8080/...) . 這樣做時,我得到Content Security Policy violated when accessing http://localhost:8080...: content-src 'self'。這讓我很困惑。在不遵守安全策略的情況下嘗試在 Jetty 中訪問我的應用程式應該會引發錯誤。但是為什么在 Jetty 中的應用程式呼叫沒有任何此類限制的 Spring Boot API 時會拋出錯誤?
我需要放寬 Jetty 服務器的內容安全策略限制嗎?如果是這樣,為什么?
摘要:
REST API:在同一 Linux VM
Jetty 服務器上運行的 Spring Boot HTTP API :如上所述的 CSP 限制 Jetty 中的
JavaScript 應用程式:呼叫 Spring Boot API
uj5u.com熱心網友回復:
簡而言之:您必須添加http://localhost:8080到default-src指令中。
; 博士;:'self'令牌是陰險的,因為你直覺地賦予他一些他無法實作的權力。
瀏覽器用來自瀏覽器地址欄的頁面 URL'self'的“元組來源”(scheme host_name port_number)替換令牌,然后他們添加一些特定于 CSP 的魔法:
- 允許
ws:主機名 ws_standard_port - 允許升級
ws:到wss:并http:以https:在CSP3的瀏覽器
那么,我們有什么:
- 您的應用程式使用 fetch 訪問 Spring Boot REST API,該 API 應包含在缺少的
connect-src指令中,因此瀏覽器default-src用作后備。 - 瀏覽器轉換
default-src 'self'為default-src http://your_domain.com:80或default-src https://your_domain.com:443(取決于您加載頁面的方式)。
正如您所看到的,這兩者都不允許http://localhost:8080。雖然實際上localhost是 的別名your_domain.com,但 CSP 并不知道這一點,只是因為host_name port_number不匹配而阻塞。
但是,如果您將使用http://localhost:8080/your_app_pathurl加載應用程式,則將允許提取到 REST API,因為'self'
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365857.html
標籤:javascript 休息 内容安全策略
