Spring Security 拒绝提供静态内容Javascript 文件

问题描述

我目前正在做一个学校项目,我正在尝试在 Spring Boot 项目上实现 Spring Security登录功能

不幸的是,我在加载 Javascript 文件方面遇到了困难,在网上搜索了所有可能的解决方案后,我仍然没有找到任何问题的答案。

我有很多关于资源的重复代码,但我只是想涵盖我的所有基础。

这是我的 Spring Security 配置类:

@Configuration
@EnableWebMvc
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer
{
@Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/**/*.js").permitAll()
                .antMatchers("/**.js").permitAll()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/*.js").permitAll()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").permitAll()
                .and()
                .logout().invalidateHttpSession(true)
                .clearauthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("logout"))
                .logoutSuccessUrl("/logout-success").permitAll();
    }

@Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/h2-console/**")
                .antMatchers("/resources/**","/static/**","/css/**","/js/**","/img/**","/icon/**");
    }

这是我的 HTML 代码,我的目标是我的通用 /static/js/script.js 文件。该文件在资源/模板/文件夹中的索引

<script type="text/javascript" th:src="@{/js/script.js}"></script>

这是我的文件夹结构,我在其中放了一个箭头来显示放置 script.js 文件的位置。

│   ├───com
│   │   └───adventurealley
│   │       └───aafcro
│   │           ├───authorization
│   │           ├───bootstrap
│   │           ├───controller
│   │           ├───model
│   │           ├───repository
│   │           ├───restcontroller
│   │           └───service
│   ├───static
│   │   ├───css
│   │   └───js -> script.js
└───templates -> index.html

不幸的是,根本无法访问任何形状或形式的 script.js 文件。在项目中无法使用Javascript是一件大事。

有人可以帮我找出问题所在吗?

提前致谢, 符文

解决方法

感谢@Eleftheria Stein-Kousathana 解决了这个问题。

需要@EnableWebSecurity,而不是@EnableWebMvc。

由于您收到未找到的响应,因此这与 Spring Security 无关。你是不是想用 @EnableWebSecurity 而不是 @EnableWebMvc 来注释你的 ApplicationSecurityConfiguration 类? @EnableWebMvc 注释将阻止默认行为 > 为静态资源提供服务。看看这个问题了解更多详情 stackoverflow.com/questions/24661289/ – Eleftheria Stein-Kousathana

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...