2017-02-04 12 views
2

大家好我想從AEM6.1實例中獲取字體與index.html在我的本地apache服務器out站點AEM實例中創建,如下所示:AEM CORS問題與字體,而正在請求由另一臺服務器

的index.html

<link rel="stylesheet" type="text/css" href="http://localhost:4502/etc/designs/geometrixx/clientlibs/css/fonts.css" /> 

內部font.css:

@font-face { 
    font-family: 'roboto'; 
    src: url('fonts/roboto_medium/Roboto-Medium-webfont.eot'); 
    src: url('fonts/roboto_medium/Roboto-Medium-webfont.eot?#iefix') format('embedded-opentype'), 
     url('fonts/roboto_medium/Roboto-Medium-webfont.woff') format('woff'), 
     url('fonts/roboto_medium/Roboto-Medium-webfont.ttf') format('truetype'), 
     url('fonts/roboto_medium/Roboto-Medium-webfont.svg#robotomedium') format('svg'); 
    font-weight: 500; 
    font-style: normal; 
} 

這是瀏覽器響應的圖像: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我嘗試了CSS文件中字體的絕對路徑,並且這些文件在物理上位於AEM內部,但我得到了相同的響應。 任何想法?

謝謝!

回答

2

以下SlingFilter應該讓你從另一個域訪問這些字體

@SlingFilter(label = "Cross-Origin Request Filter", 
     metatype = true, 
     scope = SlingFilterScope.REQUEST, 
     order = -100) 
public class CORSFilter implements Filter { 

    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, 
         FilterChain chain) throws IOException, ServletException { 

     if (response instanceof SlingHttpServletResponse) { 
      SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response; 
      slingResponse.setHeader("Access-Control-Allow-Origin", "*"); 
      slingResponse.setHeader("Access-Control-Allow-Credentials", "false"); 
     } 

     chain.doFilter(request, response); 
    } 
} 

來源:https://gist.github.com/mickleroy/5ee8ed51ac245a8b59024a4ffec7cf7f

UPDATE

我強烈建議反對這樣做,因爲它需要AEM實例可以通過公共互聯網訪問,這違背了推薦的AEM部署架構,因爲它不是由具有調度器模塊的web服務器即這種解決方法應該只用於開發。推薦的方法是(按我原來的答覆)在你的Apache配置中添加了Access-Control標題:

<FilesMatch "\.(eot|ttf|otf|woff|woff2)$"> 
    <IfModule mod_headers.c> 
     Header set Access-Control-Allow-Origin "*" 
     Header set Access-Control-Allow-Methods "GET" 
     Header set Access-Control-Allow-Credentials "false" 
    </IfModule> 
</FilesMatch> 
+0

嗨,感謝您的快速回答,但它不起作用。我需要請求存儲在AEM實例中的字體。如果您嘗試請求存儲在apache中的字體,那麼您提到的方法很有用。更多的想法? –

+0

@FedeRodriguez你是對的,我的道歉。我已經通過在AEM中設置相同標題的解決方案更新了答案。 – mickleroy

+0

這隻允許從字面上_any domain_的跨域請求,並且絕不限於字體。出於某種原因,瀏覽器實施這些限制。忽略它們會使你發現潛在的[CS​​RF攻擊](https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)) – toniedzwiedz

1

啓用所有域跨域請求,由對方回答的建議,是一個壞主意。將該片段放入您的AEM代碼中可能會危及您網站的安全。

縱觀大局,有兩種方式可以避開CORS問題:

  1. 允許從特定域跨域請求(但沒有任何域,這是potentially dangerous這可以通過設置來實現。 Access-Control-*頭。只要確保值限制在可信域。
  2. 來自同一個域即成你的資源。

    如果您使用the dispatcher mod,你可以有Apache的緩存頁面,資產和客戶端庫[R由AEM創建並簡單地從緩存中提供字體文件。瀏覽器無論如何都會碰到Apache,並且它會完全透明,無論這些文件是直接來自Apache本身還是從AEM中獲取。另外,如果您正在尋找一種快速的ad-hock解決方案來允許您在本地機器上加載字體,那麼您可以在Apache上使用mod_proxy,讓它從AEM請求字體並將它們傳遞給瀏覽器。查看Apache: Using reverse proxy and run local website查看類似的例子。

相關問題