WebSecurityConfigurerAdapter не обслуживает index.html, если его имя не указано в URL-адресе явно.

У меня есть приложение Spring Boot, основанное на этом репозитории.

Проблема в том, что я хочу обслуживать приложение UI5 в конце.

Мне нужно создать папку src\main\webapp в моем серверном приложении, чтобы вставлять туда мои статические файлы.

Для выполнения этой работы я сделал следующие шаги:

  1. В моем pom.xml у меня есть:
<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
                <executions>
                    <execution>
                        <id>copy-resources</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${basedir}/target/classes/static</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/webapp</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
  1. В моем application.properties у меня есть:
spring.resources.static-locations=classpath:src/main/webapp
  1. В моем webapp/WEB-INF/web.xml у меня есть:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    
    <welcome-file-list>
       <welcome-file>index.html</welcome-file>
    </welcome-file-list>      
    
</web-app>
  1. И, наконец, в моем файле веб-конфигурации у меня есть:
@Profile("!dev")
@Configuration
@EnableWebSecurity(debug = true)
@EnableJpaRepositories(basePackages = "me.cimply.ask.odata.repository")
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomUserDetailsService userDetailsService;

    private final JwtAuthenticationEntryPoint jwtEntryPoint;

    @Autowired
    public WebSecurityConfig(CustomUserDetailsService userDetailsService, JwtAuthenticationEntryPoint jwtEntryPoint) {
        this.userDetailsService = userDetailsService;
        this.jwtEntryPoint = jwtEntryPoint;
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/v2/api-docs", "/configuration/ui", "/swagger-resources/**", "/configuration/**",
                "/swagger-ui.html", "/webjars/**", "/index.html*", "/odata.svc/$metadata*");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(jwtEntryPoint)
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/",
                        "/favicon.ico",
                        "/**/*.json",
                        "/**/*.xml",
                        "/**/*.properties",
                        "/**/*.woff2",
                        "/**/*.woff",
                        "/**/*.ttf",
                        "/**/*.ttc",
                        "/**/*.ico",
                        "/**/*.bmp",
                        "/**/*.png",
                        "/**/*.gif",
                        "/**/*.svg",
                        "/**/*.jpg",
                        "/**/*.jpeg",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js").permitAll()
                .antMatchers("/**/api/auth/**").permitAll()
                .anyRequest().authenticated();

        http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
    
}

Проблема в том, что когда я запускаю это приложение с mvn spring-boot:run, все в порядке, и я могу посетить http://localhost:9090/, и оно обслуживает index.html без упоминания index.html в URL-адресе!.

Однако, когда я развертываю его в Tomcat или обслуживаю его с внутренним сервером Tomcat внутри Eclipse, когда я посещаю http://localhost:8080/my-app/, он не обслуживает index.html и показывает так называемый Whitelabel Error Page (404). Но если я посещаю http://localhost:8080/my-app/index.html, то он отлично обслуживает файл index.html. Кажется, в моем классе WebSecurityConfig что-то не так, и когда я посещаю /, он отправляет страницу с ошибкой.

Другой интересный момент: если я удалю эту строку из application.properties :

spring.resources.static-locations=classpath:src/main/webapp

и измените имя папки webapp на static, тогда она обслуживает index.html, когда я посещаю /. Однако тогда мое приложение UI5 не работает, и мне нужно сохранить имя этой папки, как оно определено в приложениях UI5 (например, webapp)!

Я думаю, мне нужно как-то сказать WebSecurityConfigurerAdapter, что эта папка webapp является статической, и не запускать для этого проверку безопасности!

Обратите внимание, что в этом приложении нет MVC, я много искал, и большинство решений относились к конфигурации MVC, однако я не использую MVC в этом приложении.


person MJBZA    schedule 30.07.2020    source источник