在Sping Boot 和Spring Security应用程序中提供静态Web资源

c86crjj0  于 2022-12-13  发布在  Spring
关注(0)|答案(8)|浏览(168)

我正在尝试开发Sping Boot Web应用程序,并使用Spring安全Java配置来保护它。
按照here in Spring blog的建议,将我的静态Web资源放在“src/main/resources/public”中后,我就能够获得静态资源。即在浏览器中点击**https://localhost/test.html**可以提供html内容。

问题

启用Spring Security之后,点击静态资源URL需要身份验证。
我的相关Spring Security Java配置如下所示:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http.
            authorizeRequests()
                .antMatchers("/","/public/**", "/resources/**","/resources/public/**")
                    .permitAll()
                .antMatchers("/google_oauth2_login").anonymous()
                    .anyRequest().authenticated()
                .and()
                .formLogin()
                    .loginPage("/")
                    .loginProcessingUrl("/login")
                    .defaultSuccessUrl("/home")
                    .and()
                    .csrf().disable()
                    .logout()
                        .logoutSuccessUrl("/")
                        .logoutUrl("/logout") // POST only
                .and()
                    .requiresChannel()
                    .anyRequest().requiresSecure()
                .and()
                    .addFilterAfter(oAuth2ClientContextFilter(),ExceptionTranslationFilter.class)
                    .addFilterAfter(googleOAuth2Filter(),OAuth2ClientContextFilter.class)
                .userDetailsService(userService);
        // @formatter:on
    }

我应该如何配置antMatchers以允许将静态资源放置在src/main/resources/public中?

mzaanser

mzaanser1#

有几点需要注意:

  • Ant匹配器匹配请求路径,而不是文件系统上的资源路径。
  • 放置在src/main/resources/public中的资源将从应用程序的根目录提供。例如,src/main/resources/public/hello.jpg将从http://localhost:8080/hello.jpg提供

这就是为什么您当前的匹配器配置不允许访问静态资源。要使/resources/**工作,您必须将资源放在src/main/resources/public/resources中,并在http://localhost:8080/resources/your-resource中访问它们。
当您使用 Boot 时,您可能需要考虑使用其默认值而不是添加额外的配置。SpringBoot默认允许访问/css/**/js/**/images/**/**/favicon.ico。例如,您可以有一个名为src/main/resources/public/images/hello.jpg的文件,而无需添加任何额外的配置。您可以在web method security smoke test中看到这一点,在web method security smoke test中,无需任何特殊配置即可访问Bootstrap CSS文件。

cngwdvgl

cngwdvgl2#

@Override
      public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
             .antMatchers("/resources/**"); // #3
      }

忽略任何以“/resources/"开头的请求。这类似于在使用XML命名空间配置时配置http@security=none。

nqwrtyyt

nqwrtyyt3#

这可能是一个答案(对于spring Boot 2),同时也是一个问题。

WebSecurityConfigurerAdapter

如果你不使用一个单独的安全机制,一切都是因为它是?
在旧的 Spring Boot 版本(1.5及以下)中,正如Andy威尔金森在他上面的答案中所述,默认情况下允许像public/** or static/**这样的位置。
所以总结一下这个问题/答案--如果你使用的是带有spring security的spring Boot 2,并且有一个单独的安全机制,你必须独占地允许访问任何路由上的静态内容。

@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {

private final ThdAuthenticationProvider thdAuthenticationProvider;

private final ThdAuthenticationDetails thdAuthenticationDetails;

/**
 * Overloaded constructor.
 * Builds up the needed dependencies.
 *
 * @param thdAuthenticationProvider a given authentication provider
 * @param thdAuthenticationDetails  given authentication details
 */
@Autowired
public SpringSecurityConfiguration(@NonNull ThdAuthenticationProvider thdAuthenticationProvider,
                                   @NonNull ThdAuthenticationDetails thdAuthenticationDetails) {
    this.thdAuthenticationProvider = thdAuthenticationProvider;
    this.thdAuthenticationDetails = thdAuthenticationDetails;
}

/**
 * Creates the AuthenticationManager with the given values.
 *
 * @param auth the AuthenticationManagerBuilder
 */
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {

    auth.authenticationProvider(thdAuthenticationProvider);
}

/**
 * Configures the http Security.
 *
 * @param http HttpSecurity
 * @throws Exception a given exception
 */
@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
            .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
            .antMatchers("/management/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())
            .antMatchers("/settings/**").hasAnyAuthority(Role.Role_Engineer.getValue(),
            Role.Role_Admin.getValue())

            .anyRequest()
            .fullyAuthenticated()
            .and()
            .formLogin()
            .authenticationDetailsSource(thdAuthenticationDetails)
            .loginPage("/login").permitAll()
            .defaultSuccessUrl("/bundle/index", true)
            .failureUrl("/denied")
            .and()
            .logout()
            .invalidateHttpSession(true)
            .logoutSuccessUrl("/login")
            .logoutUrl("/logout")
            .and()
            .exceptionHandling()
            .accessDeniedHandler(new CustomAccessDeniedHandler());
}

}
请注意下面这行代码,这是新代码:

.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()

如果你使用spring Boot 1.5或更低版本,你不需要明确允许这些位置(static/public/webjars等)。
下面是官方说明,新安全框架与旧版本相比有哪些变化:
Security changes in Spring Boot 2.0 M4
我希望这对某人有帮助。谢谢!祝你有愉快的一天!

vltsax25

vltsax254#

经过20多个小时的研究,这是最终的解决方案。

**步骤1.**将“MvcConfig.java”添加到项目中.

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                .addResourceHandler("/resources/**")
                .addResourceLocations("/resources/");
    }
}

**步骤2.**将configure(WebSecurity web)覆盖添加到SecurityConfig类

@Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/resources/**");
    }

**步骤3.**将所有静态资源放在 *webapp/resources/.. * 中

zfciruhq

zfciruhq5#

如果你使用的是webjars,你需要在你的configure方法中添加这个:http.authorizeRequests().antMatchers("/webjars/**").permitAll();
请确定这是第一个陈述式。例如:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

要启用webjar,您还需要具备以下条件:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }
sauutmhj

sauutmhj6#

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        String[] resources = new String[]{
                "/", "/home","/pictureCheckCode","/include/**",
                "/css/**","/icons/**","/images/**","/js/**","/layer/**"
        };

        http.authorizeRequests()
                .antMatchers(resources).permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout().logoutUrl("/404")
                .permitAll();
        super.configure(http);
    }
}
guykilcj

guykilcj7#

我的spring Boot 应用程序也遇到了同样的问题,所以我想如果能和大家分享一下我的解决方案会很好。我只是简单地配置了antMatchers来适应特定类型的文件。在我的例子中,只有js文件和js.map。下面是一个代码:

@Configuration
   @EnableWebSecurity
   public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests()
      .antMatchers("/index.html", "/", "/home", 
       "/login","/favicon.ico","/*.js","/*.js.map").permitAll()
      .anyRequest().authenticated().and().csrf().disable();
   }
  }

有趣的是,我发现antMatcher中的resources path(如***“resources/myStyle.css”)对我完全不起作用。如果您的resoruces文件夹中有一个文件夹,只需将其添加到antMatcher中,如"/myFolder/myFille.js”**,它应该会正常工作。

d7v8vwbk

d7v8vwbk8#

在最新的Spring Security 6中,不赞成使用WebSecurityConfigurerAdapter
请改为声明WebSecurityCustomizer Bean。

@Bean
 public WebSecurityCustomizer ignoringCustomizer() {
     return (web) -> web.ignoring().requestMatchers("...");
 }

相关问题