【问题标题】:Spring Boot 1.4 and Thymeleaf 2 SecuritySpring Boot 1.4 和 Thymeleaf 2 安全性
【发布时间】:2016-09-08 23:17:05
【问题描述】:

我正在尝试使用 Spring Boot 1.4 和 Thymeleaf 2。我想保护我的应用程序。这是我的安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/resources/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
}

这是我的 MVC 控制器:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("login");
    }    
}

但是,当我尝试访问 localhost:8080 时,它显示没有 css、js 的索引页面!当我通过localhost:8080/login.html 手动登录时,一切正常。我遵守 Spring 的约定 - Thymeleaf 集成和静态资源在/resources/static 下,模板在/resource/templates 下。

对我来说缺少什么?

编辑:

它以这种方式工作:

    http
        .authorizeRequests()
            .antMatchers("/css/**").permitAll()
            .antMatchers("/js/**").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
        .logout()
            .permitAll();

但是,我应该用这种方式添加静态资源下的所有文件夹吗?我好像错过了什么。

【问题讨论】:

  • 这很奇怪,但是当您将css和js文件放入src/main/resources/static/resources时,无需进一步配置即可工作

标签: java spring spring-mvc spring-security thymeleaf


【解决方案1】:

您应该将 css 和 javascript 文件添加到 src/main/webapp

现在给定你的结构如下:

webapp
|__css/myStyles.css
|__js/myjs.js
|__images/myImage.gif
|__WEB-INF

将此添加到您的安全配置中

@Override
public void configure(WebSecurity security) {
    security.ignoring().antMatchers("/css/**", "/fonts/**", "/libs/**", "/js/**", "/images/**");
}

【讨论】:

  • 我应该将所有文件夹一个一个添加吗?我想我可以使用通配符,因为将静态文件放在 resources 文件夹下是 spring-thymeleaf 的约定。
  • 如果您在 webapps 下创建资源文件夹并将所有这些文件夹添加到其中,那么只需在 antMatchers 中添加“/recources/**”也应该可以。
  • 不,不应该。资源通过/css/js 等访问,当您从 UI 访问时,即使它们位于资源下。 Spring 根据计算的 URL 进行拦截(即使它们位于该文件夹下,也不会通过 /static 的路径访问它们。运行 UI 时它已被隐藏)。
  • 嗯,得测试一下。
猜你喜欢
  • 2018-04-21
  • 2018-02-15
  • 2016-12-05
  • 2016-10-15
  • 2023-04-04
  • 2016-07-14
  • 2014-06-14
  • 2016-10-26
相关资源
最近更新 更多