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
- not register filters as beans and instantiate them manually where
they are needed 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 NullPointerException
s.
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:
- Configure Authentication as normal
- Create an instance of WebSecurityConfigurerAdapter that contains
@Order to specify which WebSecurityConfigurerAdapter should be
considered first.- The http.antMatcher states that this HttpSecurity
will only be applicable to URLs that start with /api/- 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
Spring Security 401 Unauthorized Even With Permitall
No Primary or Default Constructor Found for Interface Java.Util.List Rest API Spring Boot
Selenium Web Driver: Cannot Be Scrolled into View
Java Xmlbeans Throws Nosuchmethod Error
Dto Pattern: Best Way to Copy Properties Between Two Objects
How to Efficiently Return the Max Possible Integer With a Given Number of Digits
Why Is Git Bash Not Using the Correct Java Path as Defined in the Path Environment Variable
Beanutils Copyproperties API to Ignore Null and Specific Propertie
Convert to Int from String of Numbers Having Comma
I Want to Execute Code Every X Seconds, But Handler.Postdelayed Not Working
Java Check If a String Is Valid Json or Valid Xml or Neither
Generate Any Random Number of Any Length in Java
Simple Export and Import of a Sqlite Database on Android
How to Remove Duplicate and Sort Objects from Jsonarray Using Java
How to Check If the File Is Image
How to Change the Colors of Text and Background for Cmd in Java