2021年12月19日 星期日

[Spring Boot] Cookie Without Secure Flag

目前情況如下圖






我們可以看到endpoint api的Cookie, 它的HttpOnly和Secure是空白的

根據下面這一篇
https://stackoverflow.com/questions/34489406/adding-httponly-and-secure-flag-for-set-cookie-in-java-web-application










我們可以得知, sesson-config中可以設置安全cookie相關項目
因此, 推測在appication.properties檔案應該有相對應的配置
在看過下面這一篇
https://stackoverflow.com/questions/40974955/spring-boot-java-config-set-session-timeout
得知有server,servlet.session項目, 因此推測在他之下可能能設置cookie
很幸運的回去appication.properties檔案嘗試, 的確有cookie的設置





設置完的結果發現, JSESSIONID 的cookie secure設置確有改變, 如下圖







可是其他的cookie都沒有改變, 怎麼辦呢?
剛好我有查到這一篇
https://rules.sonarsource.com/java/tag/owasp/RSPEC-2092





可以發現在new出來Cookie的時候, 再setSecue就可以了

解決方式->在專案全局中搜尋Cookie字樣, 將其設置secure再回傳
範例

1產生一個處理類

@Component
public class CookieSecureUtils {
	public static Cookie setSecure(Cookie targetCookie) {
		targetCookie.setHttpOnly(true);
		targetCookie.setSecure(true);
		return targetCookie;
	}
}

2載入類


	@Autowired 
	private CookieSecureUtils cookieSecureUtils;

2送出cookie前,設置安全


	response.addCookie(cookieSecureUtils.setSecure(new Cookie("domain", resultObj.getString("domain"))));
	response.addCookie(cookieSecureUtils.setSecure(new Cookie("account", account)));
	response.addCookie(cookieSecureUtils.setSecure(new Cookie("lang", request.getParameter("lang"))));
成果如下圖



沒有留言:

張貼留言

invalid packging for parent POM com.xxxxxx:1.0SNAPSHOT must be "pom" but is "jar"

 出現在專案上面冒紅線, 並有紅字invalid packing...... 在本專案的原因是, 這裡有母子專案 有在子專案pom檔中聲明parent <parent> <artifactId> heima-leadnews-test </a...