How to apply spring security filter only on secured endpoints?

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I have the following Spring Security configuration:

    httpSecurity             .csrf()             .disable()             .exceptionHandling()             .authenticationEntryPoint(unauthorizedHandler)             .and()             .sessionManagement()             .sessionCreationPolicy(SessionCreationPolicy.STATELESS)             .and()             .authorizeRequests()             .antMatchers("/api/**").fullyAuthenticated()             .and()             .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

The authenticationTokenFilterBean() is applied even on endpoints that do not match /api/** expression. I also tried adding the following configuration code

@Override public void configure(WebSecurity webSecurity) {     webSecurity.ignoring().antMatchers("/some_endpoint"); } 

but this still did not solve my problem. How can I tell spring security to apply filters only on endpoints that match the secured URI expression? Thank you

回答1:

I have an application with the same requirement and to solve it I basically restricted Spring Security to a given ant match patter (using antMatcher) as follows:

http.antMatcher("/api/**").authorizeRequests() //         .anyRequest().authenticated() //         .and()         .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

You can read it as follows: for http only invoke these configurations on requests matching the ant pattern /api/** authorizing any request to authenticated users and add filter authenticationTokenFilterBean() before UsernamePasswordAuthenticationFilter. For all others requests this configuration has no effect.



回答2:

To bypass spring security for some specific endpoints do the following:

httpSecurity      .authorizeRequests()      .antMatchers("/some_endpoints").permitAll()      .anyRequest().authenticated()      .and()      ... 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!