Безопасность Spring: применить фильтр только к конечной точке - PullRequest
0 голосов
/ 11 января 2019

В настоящее время в моем сервисе есть два вида конечных точек:

  • /portal/**: мне нужно добавить фильтр PortalAuthorizationFilter
  • Остальные: мне нужно добавить фильтр OthersAuthorizationFilter

Важно, что OthersFilter не должен применяться к /portal/** вызовам.

Я создал WebSecurityConfigurerAdapter. Мой текущий код:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .addFilterBefore(new JWTExceptionHandlerFilter(objectMapper, messageSource), BasicAuthenticationFilter.class)
            .cors().and()
            .csrf().disable()
            .antMatcher("/portal/**")
            .addFilter(new PortalAuthorizationFilter())
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .addFilter(new OthersAuthorizationFilter());
    }
}

Я отлаживал этот код, когда выполняется вызов /portal/**, PortalAuthorizationFilter достигнута, но затем также достигнут OthersAuthorizationFilter.

Я не совсем понимаю, как ее решить.

Есть идеи?

Ответы [ 3 ]

0 голосов
/ 11 января 2019
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/portal/**").... //the configuration only 
              //applies when sb hitting /portal/**
    }
}

если вам нужна другая конфигурация для другого URL, вам нужно перезаписать другую WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Order(101) //@Order(100) is default
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http... //without antMatcher(...) default will be used "/**", 
                //so it take all request. So the order of this class should be 
                // higher
    }
}

Если вы хотите использовать подход фильтра (.addFilter(new OthersAuthorizationFilter());), то в вашем методе doFilter вы должны реализовать:

doFilter(...) {
  if(match(request, "/portal/**")
    ....
}

К сожалению AuthenticationProvider не даст вам такой возможности, он не знает о URL, только учетные данные. Если вы хотите больше , прочитайте Spring-Security-Architecture .

Но я хочу, чтобы делегировал авторизацию

0 голосов
/ 15 января 2019

Другой вариант - использовать шаблон делегата. Представьте, если у вас есть фильтр, который выглядит так

public class PickAndChooseFilter extends OncePerRequestFilter {

    private AntPathRequestMatcher matcher = new AntPathRequestMatcher("/portal/**");
    private final Filter portalAuthorizationFilter;
    private final Filter othersAuthorizationFilter;

    public PickAndChooseFilter(Filter portalAuthorizationFilter, Filter othersAuthorizationFilter) {
        this.portalAuthorizationFilter = portalAuthorizationFilter;
        this.othersAuthorizationFilter = othersAuthorizationFilter;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        if (matcher.matches(request)) {
            portalAuthorizationFilter.doFilter(request, response, filterChain);
        } else {
            othersAuthorizationFilter.doFilter(request, response, filterChain);
        }
    }
}

тогда вместо

.addFilter(new PortalAuthorizationFilter())
.addFilter(new OthersAuthorizationFilter())

у тебя просто было бы

.addFilter(new PickAndChooseFilter(
    new PortalAuthorizationFilter(),
    new OthersAuthorizationFilter()
)
0 голосов
/ 11 января 2019

Вам необходимо создать другой класс конфигурации, который также расширит WebSecurityConfigurerAdapter, там вы сопоставите свой URL с antMatchers и добавите свой фильтр. Какое бы сопоставление с образцом не запустило эту конфигурацию безопасности Прочитайте это сообщение

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...