我正在 HTML 文件(thymeleaf 模板)中使用 Spring Security 和 Bootstrap 构建 Spring MVC 应用程序。 Spring Security部分基于Spring Guide对于春季安全 http://spring.io/guides/gs/securing-web/并与 Spring Boot 应用服务器相结合。
启用 Spring Security 后,引导 css 文件将无法加载,并显示错误消息:
Refused to execute script from 'http://localhost:8080/js/bootstrap.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
上面的错误消息来自 chrome 开发者控制台。
我尝试过的:
- 禁用 Spring Security
=> bootstrap css 再次工作,但我需要安全性
- 在 spring 论坛上搜索,但有一个循环链接,没有解决方案
- 添加资源处理程序,但我看不到处理程序被调用,错误也消失
- 添加资源路径
permit
call
我的目录结构:
/main
|-> /java
| BootStart.java
|-> /security
|SecurityConfiguration.java
|-> /resources
|-> /static
|-> /css /** bootstrap location */
|-> /js
|-> /fonts
|-> /templates
| /user
| sample.html
BootStart.java 是 Spring Boot 获取的 java 文件。
BootStart.java:
@EnableAutoConfiguration
@ComponentScan
public class BootStart {
public static void main(String[] args) {
SpringApplication.run(BootStart.class, args);
}
}
安全配置.java:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
http
.authorizeRequests()
.antMatchers("/", "/resources/static/**").permitAll()
.anyRequest().authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
示例.html:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}" href="../../css/bootstrap.min.css"/>
<link rel="stylesheet" th:href="@{/css/bootstrap-theme.css}" href="../../css/bootstrap-theme.min.css"/>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div class="alert alert-danger" role="alert">!Basic template!</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
目前我在我的 pom 中使用以下依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
我必须如何配置 Spring Security 才能从 /static 资源目录加载 css/js 文件?