Spring Security больше не перенаправляет на страницу входа после обновления до Spring Boot 1.5-2, Spring Security 4-5.

У меня есть приложение OAUTH2, в котором конечные точки oauth2 защищены Spring Security, поэтому некоторые страницы защищены логином на основе формы.

Раньше, если я нажимал на один из этих URL-адресов, меня правильно перенаправляли на страницу входа.

Я только что обновился с Spring Boot 1.5.16 до Spring Boot 2.0.6. что привело к обновлению через зависимости Spring Security с 4.2.8 до 5.0.9.

Теперь, если я нажму URL-адрес, по которому я не вошел в систему, я просто получу страницу, подобную этой:

<oauth>
  <error_description>
    Full authentication is required to access this resource
  </error_description>
  <error>unauthorized</error>
</oauth>

Более того, если я попытаюсь попасть на страницу входа, у меня нет на это полномочий. Кто-нибудь понял, в чем причина этого? Порядок фильтра возможно?

Вот как выглядит моя конфигурация безопасности:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final AuthenticationManager authenticationManager;

    private final Environment environment;

    @Autowired
    public SecurityConfig(AuthenticationManager authenticationManager, Environment environment) {
        this.authenticationManager = authenticationManager;
        this.environment = environment;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().
                headers().frameOptions().disable().and()
                .formLogin().loginPage("/login").permitAll()
                .and()
                .requestMatchers().antMatchers("/login", "/logout", "/oauth/authorize", "/oauth/confirm_access")
                .and()
                .authorizeRequests().anyRequest().authenticated();
    }
}

и это цепочка фильтров, которая создается:

2018-10-19 15:22:10.865  INFO 19012 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/oauth/token'], Ant [pattern='/oauth/token_key'], Ant [pattern='/oauth/check_token']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@737f44b6, org.springframework.security.web.context.SecurityContextPersistenceFilter@61f7a8e9, org.springframework.security.web.header.HeaderWriterFilter@139be706, org.springframework.security.web.authentication.logout.LogoutFilter@60b40eca, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@7467a12, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@4fd13263, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@1d003890, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@6e762f08, org.springframework.security.web.session.SessionManagementFilter@13f07542, org.springframework.security.web.access.ExceptionTranslationFilter@2e2ecd3a, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@65db717c]
2018-10-19 15:22:10.880  INFO 19012 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher@4432df93, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@c48f5fc, org.springframework.security.web.context.SecurityContextPersistenceFilter@731455ec, org.springframework.security.web.header.HeaderWriterFilter@67e583c6, org.springframework.security.web.authentication.logout.LogoutFilter@7bc67409, org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter@4c112545, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@16762cc2, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@5dc67679, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@5473e34c, org.springframework.security.web.session.SessionManagementFilter@4e9d0777, org.springframework.security.web.access.ExceptionTranslationFilter@750210bc, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@d7ab665]
2018-10-19 15:22:10.895  INFO 19012 --- [  restartedMain] o.s.s.web.DefaultSecurityFilterChain     : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/login'], Ant [pattern='/logout'], Ant [pattern='/oauth/authorize'], Ant [pattern='/oauth/confirm_access']]], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@22671580, org.springframework.security.web.context.SecurityContextPersistenceFilter@412e0841, org.springframework.security.web.header.HeaderWriterFilter@60f6611f, org.springframework.security.web.authentication.logout.LogoutFilter@24ec00c6, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@1531681a, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@242e419a, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@77833299, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@2ea3b229, org.springframework.security.web.session.SessionManagementFilter@38fd683f, org.springframework.security.web.access.ExceptionTranslationFilter@7e4364ca, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@63dad600]
201

person PaulNUK    schedule 19.10.2018    source источник
comment
Вы ознакомились с руководством по миграции? (Spring Boot)[github.com/ spring-projects/spring-boot/wiki/ & (Spring Security)[github.com/spring-projects/spring-boot/wiki/   -  person Randy Casburn    schedule 19.10.2018
comment
Да ничем не выделялся.   -  person PaulNUK    schedule 19.10.2018
comment
Я бы рассмотрел этот github .com/spring-projects/spring-boot/wiki/ По сути, любая безопасность, на которую вы полагались с помощью Boot, больше не доступна в версии 2.x.   -  person Rob Winch    schedule 19.10.2018
comment
Оказалось, что это был заказ фильтра.   -  person PaulNUK    schedule 30.01.2019
comment
@PaulNUK Привет. Извините, но я не смог найти решение вышеупомянутой проблемы. Не могли бы вы уточнить, поскольку я столкнулся с той же проблемой. Заранее спасибо.   -  person Vibhav Chaddha    schedule 26.04.2019


Ответы (1)


Это работает для меня

    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
            http.authorizeRequests().
            antMatchers("/db*/**").fullyAuthenticated().
            antMatchers("/rest/**").permitAll().
            and().formLogin().  //login configuration
            loginPage("/index.jsf?faces-redirect=true");
        }
    }

и в URL-адресе вы должны указать localhost: 8080/db/, и он будет автоматически перенаправлен на вашу индексную страницу.

person Aneesh Mathai    schedule 30.01.2019