問題描述
在整合 Spring Boot、Spring Security、Thymeleaf 的練習中,對頁面進行調試時,發現如下錯誤提示:
Refused to execute script from 'http://localhost:8080/codelib-springsecurity-sample-web/js/ie10-viewport-bug-workaround.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
解決過程
1、 首先看到 “because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled”,因為 Thymeleaf 對於頁面的元素必須是嚴格的格式,所以我以為是因為我頁面代碼上沒有加 type="text/javascript" 的原因。
<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>
結果加上了並不能解決問題。
2、 再看 “Refused to execute script ...”,為什么會被拒絕執行呢?進而想到可能是權限的控制問題,亦即是 Spring Security 的靜態資源訪問配置問題。經核查,的確是這樣的問題。
正確配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
// http.authorizeRequests()每個匹配器按照它們被聲明的順序被考慮。
http
.authorizeRequests()
// 所有用戶均可訪問的資源
.antMatchers("/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico", "/index").permitAll()
// ROLE_USER的權限才能訪問的資源
.antMatchers("/user/**").hasRole("USER")
// 任何尚未匹配的URL只需要驗證用戶即可訪問
.anyRequest().authenticated()
.and()
.formLogin()
// 指定登錄頁面,授予所有用戶訪問登錄頁面
.loginPage("/login")
.permitAll()
.and()
.headers()
.frameOptions().sameOrigin();
}
問題在於我原來配置中沒有將 "/js/**" 的路徑添加到配置中,導致沒有驗證的用戶沒有權限訪問。
總結
項目結構如下,假如我要能否訪問 plugins 文件夾下的文件,也需要將 “/plugins/**” 添加到相應到上述的配置中,允許所有請求訪問。
注:對於Spring Boot 整合 Thymeleaf,靜態資源默認存放在 static 文件夾下,在頁面上寫路徑上不需要加上 static 路徑,而 html 頁面則放在 templates 文件夾下。
所以寫法如下:
<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>