在整合 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.css
一、 首先看到 「because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled」,由於 Thymeleaf 對於頁面的元素必須是嚴格的格式,因此我覺得是由於我頁面代碼上沒有加 type="text/javascript" 的緣由。html
<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>
結果加上了並不能解決問題。java
二、 再看 「Refused to execute script ...」,爲何會被拒絕執行呢?進而想到多是權限的控制問題,亦便是 Spring Security 的靜態資源訪問配置問題。經覈查,的確是這樣的問題。
正確配置以下:web
@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/**" 的路徑添加到配置中,致使沒有驗證的用戶沒有權限訪問。spring
項目結構以下,假如我要可否訪問 plugins 文件夾下的文件,也須要將 「/plugins/**」 添加到相應到上述的配置中,容許全部請求訪問。
ide
注:對於Spring Boot 整合 Thymeleaf,靜態資源默認存放在 static 文件夾下,在頁面上寫路徑上不須要加上 static 路徑,而 html 頁面則放在 templates 文件夾下。調試
因此寫法以下:code
<script th:src="@{js/ie-emulation-modes-warning.js}" src="../static/js/ie-emulation-modes-warning.js" type="text/javascript"></script>