Подтвердить что ты не робот

Конфигурация безопасности с помощью Spring -boot

Я создал класс конфигурации Spring для Spring -Boot. Моя страница входа имеет ресурсы css, js и файлы ico. Ресурсы получают отказ по соображениям безопасности и каждый раз перенаправляются на страницу входа в систему. Почему EnableWebMVCSecurity не добавляет местоположение ресурса в Classpath. После изменения кода, как и во втором фрагменте, добавляется расположение ресурса я Classpath. не понимаю, что мне не хватает для ресурсов в первом фрагменте кода.


@Configuration

/*
 * Enable Spring Security’s web security support and provide the Spring MVC integration
 * It also extends WebSecurityConfigurerAdapter and overrides a couple of its methods to set some specifics of the web security configuration.
 */
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

/**
 * The configure(HttpSecurity) method defines with URL paths should be 
     * secured and which should not. 
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        .authorizeRequests()
            .anyRequest().authenticated();

//      There is a custom "/login" page specified by loginPage(), and everyone 
//      is allowed to view it.      
        http
            .formLogin()
                .loginPage("/login.html")
                .permitAll()
                .and()
            .logout()
                .permitAll().logoutSuccessUrl("/login.html");
    }

    @Configuration
    protected static class AuthenticationConfiguration extends
            GlobalAuthenticationConfigurerAdapter {
        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
//          As for the configure(AuthenticationManagerBuilder) method, it sets up 
//          an in-memory user store with a single user. That user is given a 
//          username of "user", a password of "password", and a role of "USER".
            auth
                    .inMemoryAuthentication()
                    .withUser("[email protected]").password("password").roles("USER");
        }
   }

Я получил эту работу, изменив код на


@Configuration
/*
 * Enable Spring Security’s web security support and provide the Spring MVC integration
 * It also extends WebSecurityConfigurerAdapter and overrides a couple of its methods to set some specifics of the web security configuration.
 */
public class WebSecurityConfig{

    @Bean
    public ApplicationSecurity applicationSecurity() {
        return new ApplicationSecurity();
    }

    @Bean
    public AuthenticationSecurity authenticationSecurity() {
        return new AuthenticationSecurity();
    }

    @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
    protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
            .authorizeRequests()
                .anyRequest().authenticated();
            http
                .formLogin()
                    .loginPage("/login.html")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll().logoutSuccessUrl("/login.html");

        }
    }

    @Order(Ordered.HIGHEST_PRECEDENCE + 10)
    protected static class AuthenticationSecurity extends
            GlobalAuthenticationConfigurerAdapter {
        @Override
        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth
            .inMemoryAuthentication()
            .withUser("[email protected]").password("password").roles("USER");

        }
    }   
}

После изменения кода я заметил, что пути Игнорировать были добавлены в фильтр, и я вижу следующее в журналах:

[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/css/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/js/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/images/**'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: Ant [pattern='/**/favicon.ico'], []
[ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: [email protected]1, [org.springframework.secu[email protected]4e3e0069, org.spring[email protected]3d2dd0cf, [email protected]b02, [email protected], org.[email protected]267237ef, org.springframework.s[email protected]129495ef, org.springframework.[email protected]7db0a467, org.springfram[email protected]764d1dbd, org.sp[email protected]25a5268d, org.springframework.[email protected]15c01d0c, org.springfram[email protected]37818a3b, o[email protected]3fe57e49, org[email protected]4278af59, org.springfr[email protected]424bef91]
4b9b3361

Ответ 1

В docs вы отключили загрузочный автозапуск spring в первом примере с помощью @EnableWebSecurity, поэтому вам придется явно игнорировать все статические ресурсы вручную. Во втором примере вы просто предоставляете WebSecurityConfigurer, который является аддитивным поверх autoconfig по умолчанию.

Ответ 2

Создайте файл Конфигурация, который расширяет WebSecurityConfigurerAdapter и аннотирует класс @EnableWebSecurity

Вы можете переопределить методы типа configure(HttpSecurity http), чтобы добавить базовую безопасность, как показано ниже

@Configuration
@EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
        http
            .csrf().disable()
            .authorizeRequests()
                .anyRequest().permitAll();
        }
}

Ответ 3

Добавьте ниже метод обхода безопасности для CSS и JS в конфигурации безопасности -

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