Исключить пользовательский фильтр для некоторых URL в Spring Boot - PullRequest
0 голосов
/ 24 октября 2019

У меня есть приложение с весенней загрузкой, которое использует аутентификацию OAuth. Помимо аутентификации, мне нужно авторизовать пользователей, прежде чем они смогут получить доступ к системе. Я создал собственный фильтр, который авторизует пользователя. Я просто хочу запустить этот фильтр только после BasicAuthenticationFilter. Если BasicAuthenticationFilter не запускается, мой фильтр также не должен запускаться.

AuthorizationFilter.java

@Component
public class AuthorizationFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        boolean isValidUser = true;
        // we get the authenticated user from the context
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String id = (authentication == null)? "" : authentication.getName();

        ..
        // code to get the user data from database using 'id' and set isValidUser flag
        ..
        if(isValidUser) {
            filterChain.doFilter(request, response);
        }
        else {
            ...
            // handle UNAUTHORIZED
            ...
        }
    }
}

SecurityConfiguration.java

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(final HttpSecurity security) throws Exception {

        security.requestMatchers()
                .antMatchers("/actuator/health")
                .and()
                .authorizeRequests()
                .antMatchers("/actuator/health").permitAll()
                .and()
                .csrf().disable();

        security.cors();

        // Custom filter to validate if user is authorized and active to access the system
        security.addFilterAfter(new AuthorizationFilter(), BasicAuthenticationFilter.class);
    }
}

Вопросы:

  1. Даже если я разрешил конечную точку «/ привод / здоровье», мой пользовательский фильтр все еще работает для этой конечной точки. Как я могу исключить мой фильтр из режима «/ привод / здоровье»?

  2. Идеальным решением было бы запустить мой фильтр, только если работает BasicAuthenticationFilter. Это возможно? Как?

1 Ответ

0 голосов
/ 28 октября 2019

AFAIK, лучшее решение для подобных проблем - создать новую цепочку фильтров. В вашем случае была бы цепочка фильтров для конечных точек, которым требуется аутентификация, и другая цепочка фильтров для открытых конечных точек (не нуждающихся в какой-либо аутентификации). Вот пример цепочки фильтров для незащищенных конечных точек:

<bean id="openFilterChain" class="org.springframework.security.web.DefaultSecurityFilterChain">
    <description>Pass the list of filters that you want to invoke for the given request matcher.</description>
    <constructor-arg index="0" ref="infoRequestMatcher"/>
    <constructor-arg index="1">
        <list>
            <ref bean="exceptionTranslationFilter"/>
        </list>
    </constructor-arg>
</bean>

<bean id="infoRequestMatcher" class="org.springframework.security.web.util.matcher.AntPathRequestMatcher">
    <description>
        Pass the request matcher that matches all you unprotected endpoints.
    </description>
    <constructor-arg index="0" value="/actuator/health"/>
</bean>

<bean id="springSecurityFilterChain" class="org.springframework.security.web.FilterChainProxy">
    <description>
        Register your custom filter chain here.
    </description>
    <constructor-arg>
        <list>
            <ref bean="openFilterChain"/>
            <ref bean="otherSecurityFilterChain"/>
        </list>
    </constructor-arg>
</bean>
...