如何在Java Jersey Framework下將Cache-Control屬性新增至APIs的Response Headers
此篇文章主要是要解決Cache Management: Insecure Policy ( 11306 )的issue,查看了關於這個issue的報告說明之後,主要是指出API中的Response Header裡面沒有加上Cache Control行為,於是上網搜尋了一下關於什麼是Cache Control。
主要有三種設定方式:
Cache-control: private
Cache-Control: no-store
Cache-Control: no-cache
- Cache-Control: private; 這情境用在敏感資料的處理策略,通常在關閉瀏覽器或切換作業系統使用者的過程就會被刪除。
- Cache-Control: no-store; 完全不存下來,所以完全沒有cache。
- Cache-Control: no-cache; 會進行cache,但還是會每次都問有沒有新內容。
而根據資安報告的檢測建議的解決方式為:
Set Cache-Control directive to private, no-cache and/or no-store.
接下來就把Cache-Control加入到API的Response Header中吧!
首先,介紹一下開發工具,使用的是Eclipse Mars 4.5版
Step 1:
於專案上點選右鍵,並新增一個Filter file(筆者在這將檔案命名為NoCacheFilter)
Step 2:
於我們新增好的Filter file中的public void doFilter區塊內新增程式碼
新增的程式碼區塊內容如下:
首先必須新增一個HttpServletResponse物件
再將Cache-Control增加到response header中
接下來我們來看一下API的Response Header是否已經有新增完成Cache-Control屬性,打開Chrome的開發者工具檢視一下
這樣就完成囉!
參考資料: