Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply spring security filter only on secured endpoints?

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?

like image 847
Bravo Avatar asked Apr 22 '16 14:04

Bravo


People also ask

How do you make a Spring Security filter?

Spring security provides few options to register the custom filter. We can use one of them based on our requirement. addFilterAfter(filter, class)–Adds a filter after the position of the specified filter class. addFilterBefore(filter, class)–Filter before the position of the specified filter class.

Which filter class is required for Spring Security?

Spring Security's web infrastructure is based entirely on standard servlet filters. It doesn't use servlets or any other servlet-based frameworks (such as Spring MVC) internally, so it has no strong links to any particular web technology.

What is authentication filter in Spring Security?

Class AuthenticationFilterA Filter that performs authentication of a particular request. An outline of the logic: A request comes in and if it does not match setRequestMatcher(RequestMatcher) , then this filter does nothing and the FilterChain is continued.


1 Answers

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.

like image 162
Francisco Spaeth Avatar answered Sep 19 '22 08:09

Francisco Spaeth