Spring Security Configuration Filter Any Requests Except a Specific Endpoint

Spring Security Configuration filter any requests except a specific endpoint?

The way I solved in an old project is requiring auth on every endpoint

http.authorizeRequests()
.anyRequest().authenticated()
.and()
.addFilterAfter(new JWTAuthenticationFilter(),UsernamePasswordAuthenticationFilter.class)

and ignoring security on the desired endpoints

 public void configure(WebSecurity web) {
web.ignoring().antMatchers(HttpMethod.POST, "/users/login");
}

Spring Security add filter to all Endpoint EXCEPT one

thanks to kimhom and his answer in combination with Nicholas and e.g.78 i figured it out - web.ignoring does not work, for reasons i want to investigate later - what i forgot about is, that spring will automatically add all filters present as Beans to all filter chains. to prevent this, one can either

  1. not register filters as beans and instantiate them manually where
    they are needed
  2. add a FilterRegistrationBean for the filters in
    question and disable registration for them like this:

    @Bean
    public FilterRegistrationBean disableMyFilterBean(MyFilterBean filter) {
    FilterRegistrationBean registration = new FilterRegistrationBean(filter);
    registration.setEnabled(false);
    return registration;
    }

Then my filters are only applied where i want them to - i do not even need to provide WebSecurity.ignoring matchers

How to apply Spring Security filter only on secured endpoints?

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.

Use Spring Security Filter to lock down everything except a few routes

We're reworking our product to remove the default "anonymousUser"
behavior in Spring Security

I'm wondering what you mean by this. Based on the rest of the description, I don't think you need the following (i.e. you should remove it):

anonymous().disabled()

The above says that the user will be null if no user is authenticated, which tends to lead to NullPointerExceptions.

Remember that for authorizeRequests() (or for <intercept-url> ) ordering matters. The Java configuration you have (reformatted slightly for readability)

.authorizeRequests()
.antMatchers("/**").authenticated()
.antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
.and()

is going to use the following logic:

  • Does this request match "/**"?
    • Yes, everything matches "/**". So every request requires the user to be authenticated.
  • Ignore every other rule because we already matched

Instead you should use the following:

.authorizeRequests()
.antMatchers("/", "/login", "/mobile/login", "/api/auth/**", "/reservations/**").permitAll()
.anyRequest().authenticated()
.and()
  • Does the request match "/", or "/login", or ...?
    • If yes, then anyone is allowed to access it and STOP (no more rules are used).
    • If the request does not match, then continue.
  • Does the request match any request?
    • Yes, so if the request does not match a previous rule, then it will require the user to be authenticated.

NOTE: antMatchers("/**") is more concisely represented as anyRequest().

Disabling a filter for only a few paths in spring security

In your custom AuthenticationFilter you can define a RequestMatcher and use it before doing your logic, like so:

public class AuthenticationFilter extends OncePerRequestFilter {
private final RequestMatcher ignoredPaths = new AntPathRequestMatcher("/swagger-ui");

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
if (this.ignoredPaths.matches(request)) {
filterChain.doFilter(request, response);
return;
}

// do your logic
filterChain.doFilter(request, response);
}
}

How to add a filter only for one special path WebSecurityConfigurerAdapter

Looks like you can't do that with a single Configuration class. Take a look at this question: How to apply spring security filter only on secured endpoints?.

In this case, I think the better solution is to configure multiple HttpSecurity. From Spring IO documentation:

We can configure multiple HttpSecurity instances just as we can have
multiple blocks. The key is to extend the
WebSecurityConfigurationAdapter multiple times. For example, the
following is an example of having a different configuration for URL’s
that start with /api/.

The documentation has a full example with the necessary steps to accomplish this:

  1. Configure Authentication as normal
  2. Create an instance of WebSecurityConfigurerAdapter that contains
    @Order to specify which WebSecurityConfigurerAdapter should be
    considered first.
  3. The http.antMatcher states that this HttpSecurity
    will only be applicable to URLs that start with /api/
  4. Create another instance of WebSecurityConfigurerAdapter. If the URL does not start with /api/ this configuration will be used. This
    configuration is considered after ApiWebSecurityConfigurationAdapter
    since it has an @Order value after 1 (no @Order defaults to last).

Good luck!



Related Topics



Leave a reply



Submit