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

Добавить фильтр защиты http в java config

Я пытаюсь добавить веб-безопасность в spring, но я не хочу, чтобы фильтр применялся к определенным вещам. Как это делается в java?

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

В целом, я хочу сделать следующее:

/resources/** НЕ ДОЛЖНО проходить фильтр, /login (POST) НЕ ДОЛЖЕН проходить фильтр, все остальное СЛЕДУЕТ пройти фильтр

В рамках различных примеров, которые я нашел через spring, я смог придумать это как для начала, но явно не работает:

@Configuration
@EnableWebSecurity
@Import(MyAppConfig.class)
public class MySecurityConfig extends WebSecurityConfigurerAdapter
{
    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity.ignoring().antMatchers("/resources/**");
    }

    @Override
    public void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                .authorizeRequests()
                .antMatchers("/resources/**").permitAll()
                .antMatchers("/login").permitAll();

        httpSecurity.httpBasic();
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    @Autowired
    public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor(MyTokenUserInfoCache userInfoCache, ServerStatusService serverStatusService, HttpSecurity httpSecurity) throws Exception
    {
        TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
        TokenFilterSecurityInterceptor<TokenInfo> tokenFilter = new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");
        httpSecurity.addFilter(tokenFilter);
        return tokenFilter;
    }
}
4b9b3361

Ответ 1

Вас интересует все Spring Безопасность, игнорирующая URL-адреса, или вы хотите, чтобы только этот фильтр игнорировал запрос? Если вы хотите, чтобы все Spring Security игнорировали запрос, это можно сделать, используя следующее:

@Configuration
@EnableWebSecurity
@Import(MyAppConfig.class)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyTokenUserInfoCache userInfoCache;
    @Autowired
    private ServerStatusService serverStatusService;

    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity
            .ignoring()
                // All of Spring Security will ignore the requests
                .antMatchers("/resources/**")
                .antMatchers(HttpMethod.POST, "/login");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .addFilter(tokenInfoTokenFilterSecurityInterceptor())
            .authorizeRequests()
                // this will grant access to GET /login too do you really want that?
                .antMatchers("/login").permitAll()
                .and()
            .httpBasic().and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor() throws Exception
    {
        TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
        return new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");
    }
}

Если вы хотите, чтобы только этот конкретный фильтр игнорировал определенные запросы, вы можете сделать что-то вроде этого:

@Configuration
@EnableWebSecurity
@Import(MyAppConfig.class)
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private MyTokenUserInfoCache userInfoCache;
    @Autowired
    private ServerStatusService serverStatusService;

    @Override
    public void configure(WebSecurity webSecurity) throws Exception
    {
        webSecurity
            .ignoring()
                // ... whatever is here is ignored by All of Spring Security
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
            .addFilter(tokenInfoTokenFilterSecurityInterceptor())
            .authorizeRequests()
                // this will grant access to GET /login too do you really want that?
                .antMatchers("/login").permitAll()
                .and()
            .httpBasic().and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Bean
    public TokenFilterSecurityInterceptor<TokenInfo> tokenInfoTokenFilterSecurityInterceptor() throws Exception
    {
        TokenService<TokenInfo> tokenService = new TokenServiceImpl(userInfoCache);
        TokenFilterSecurityInterceptor tokenFilter new TokenFilterSecurityInterceptor<TokenInfo>(tokenService, serverStatusService, "RUN_ROLE");


        RequestMatcher resourcesMatcher = new AntPathRequestMatcher("/resources/**");
        RequestMatcher posLoginMatcher = new AntPathRequestMatcher("/login", "POST");
        RequestMatcher ignored = new OrRequestMatcher(resourcesMatcher, postLoginMatcher);
        return new DelegateRequestMatchingFilter(ignored, tokenService);
    }
}


public class DelegateRequestMatchingFilter implements Filter {
    private Filter delegate;
    private RequestMatcher ignoredRequests;

    public DelegateRequestMatchingFilter(RequestMatcher matcher, Filter delegate) {
        this.ignoredRequests = matcher;
        this.delegate = delegate;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) {
         HttpServletRequest request = (HttpServletRequest) req;
         if(ignoredRequests.matches(request)) {
             chain.doFilter(req,resp,chain);
         } else {
             delegate.doFilter(req,resp,chain);
         }
    }
}

Ответ 2

1 В xml-конфигурации spring -security я использую

<http pattern="/resources/**" security="none"/> 

<http use-expressions="true">
<intercept-url pattern="/login" access="permitAll"/> 
</http>    

чтобы извлечь его из проверки безопасности.

2 После этого добавьте тег mvc:resource в конфигурацию spring

<mvc:resources mapping="/resource/**" location="/resource/"/>

Важно: этот конфиг будет работать только в том случае, если URL-адрес обрабатывается сервлетом диспетчера. Это означает, что в web.xml вы должны иметь

   <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>