Difference between requestMatchers().mvcMatchers( and mvcMatcher( - spring

I know that requestMatchers specifies to which requests the security check applies but there is also mvcMatcher which is pretty similar. Can they be used interchangeably?
e.g.
#Override
public void configure(HttpSecurity httpSecurity)
httpSecurity.requestMatchers().mvcMatchers("/*")...
vs
#Override
public void configure(HttpSecurity httpSecurity)
httpSecurity.mvcMatcher("/*")...

There is no big difference between those two methods. When you have a simple configuration with a single path, you can use mvcMatcher("/api/**") for example.
When a more advanced configuration is necessary, you can use requestMatchers(...) or requestMatcher(...), like so:
http
.requestMatchers()
.mvcMatchers("/api/**")
.mvcMatchers("/admin/**")
.requestMatchers(myCustomRequestMatcher())
If you look at the source code, the mvcMatchers() method call the requestMatcher() method:
public HttpSecurity mvcMatcher(String mvcPattern) {
HandlerMappingIntrospector introspector = new HandlerMappingIntrospector(getContext());
return requestMatcher(new MvcRequestMatcher(introspector, mvcPattern));
}

Related

Spring Security add/remove antMatchers and roles dynamically at runtime

Is there a way to change this place dynamically? In other words, invoke the method that adds or removes antMatchers or override completely. map roles, etc.
#EnableWebSecurity
public class WebSecurityConfigAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
//Change this configs dynamically at runtime
}
}
In Spring Security version 5.6, which is in 5.6.0.M3 as of now, you can create an AuthorizationManager bean and define place your rules anywhere you want, like so:
#Autowired
private MyCustomAuthorizationManager access;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().access(access);
}
Or even better, you can define a SecurityFilterChain bean and make use of method parameter injection, instead of extending WebSecurityConfigurerAdapter:
#Bean
SecurityFilterChain app(HttpSecurity http, MyCustomAuthorizationManager access) throws Exception {
...
http.authorizeRequests().access(access);
...
return http.build();
}
There is a great presentation showing how to do this.
I ended up with this solution. The solution is to close the current context and run the new one. Of course, it has the disadvantage because it causes downtime but I use a load balancer and several nodes so it's was ok for me.

Spring security: How can I enable anonymous for some matchers, but disable that for the rest?

I am trying to enable the anonymous access to some part of my rest api, but disable that to the rest.
I tried config looks like:
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anonymous().and()
.antMatchers(SOME_URL).authenticated()
.and()
.anoymous().disable()
.antMatchers(OTHER_URL).authenticated();
}
But later, I realized that the later anonymous().disable will cover the previous setting.
So is anyone can give me some suggestion that how can I enable the anonymous for part of my url?
Many thanks!!!
You can define a RequestMatcher, one for public urls and other for protected urls. Then, override the configure method which accepts WebSecurity as param. In this method, you can configure web to ignore your public urls.
private static final RequestMatcher PUBLIC_URLS = new OrRequestMatcher(
new AntPathRequestMatcher("/public/**")
);
private static final RequestMatcher PROTECTED_URLS = new NegatedRequestMatcher(PUBLIC_URLS);
#Override
public void configure(final WebSecurity web) {
web.ignoring().requestMatchers(PUBLIC_URLS);
}
#Override
protected void configure(final HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(STATELESS)
.and()
.exceptionHandling()
// this entry point handles when you request a protected page and you are not yet
// authenticated
.defaultAuthenticationEntryPointFor(forbiddenEntryPoint(), PROTECTED_URLS)
.anyRequest()
.authenticated();
// and other clauses you would like to add.
}

How to disable spring security for certain resource paths

I am implementing spring security in a spring boot application to perform JWT validation where I have a filter and an AuthenticationManager and an AuthenticationProvider. What I want to do is that I want to disable security for certain resource paths (make them unsecure basically).
What I have tried in my securityConfig class (that extends from WebSecuirtyConfigurerAdapater) is below:
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
UsernamePasswordAuthenticationFilter.class);
httpSecurity.authorizeRequests().antMatchers("/**").permitAll();
httpSecurity.csrf().disable();
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
What I am trying to do right now is that I want to make all my resource paths to be un-secure,
but the above code doesn't work and my authenticate method in my CustomAuthenticationProvider (that extends from AuthenticationProvider) get executed every time
Authentication piece gets executed irrespective of using permitAll on every request. I have tried anyRequest too in place of antMatchers:
httpSecurity.authorizeRequests().anyRequest().permitAll();
Any help would be appreciated.
Override the following method in your class which extends WebSecuirtyConfigurerAdapater:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/unsecurePage");
}
try updating your code in order to allow requests for specific paths as below
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.addFilterBefore(buildJwtTokenAuthenticationProcessingFilter(),
UsernamePasswordAuthenticationFilter.class);
httpSecurity.authorizeRequests().antMatchers("/").permitAll().and()
.authorizeRequests().antMatchers("/exemptedPaths/").permitAll();
httpSecurity.csrf().disable();
httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

Spring Security Java Config same url allowed for anonymous user and for others authentication needed

In Spring Security Java Config
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/guest/**").authenticated;
}
What if I want this same url to be allowed access to a particular principal or a User.
And others Authentication needed. Is it possible?
If you want to completely bypass any security checks for certain URLs, you could do the following:
#Override
public void configure(WebSecurity web) throws Exception {
// configuring here URLs for which security filters
// will be disabled (this is equivalent to using
// security="none")
web
.ignoring()
.antMatchers(
"/guest/**"
)
;
}
This is equivalent to the following XML snippet:
<sec:http security="none" pattern="/guest/**" />
Two approaches; first, use HttpSecurity#not() like this to block anonymous users;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/guest/**")
.not().hasRole("ANONYMOUS");
// more config
}
Or use something like ROLE_VIEW_GUEST_PAGES that gets added depending on the user type from your UserDetailsService. This, IMO gives you better control over who sees guest pages.
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/guest/**")
.hasRole("VIEW_GUEST_PAGES");
// more config
}

Spring Security Java Config - dynamic IP list for a Request URL

I have two configuration. The first would like to achieve that all requests from(/api/**) must come only from a determined ip.
like Following...
.authorizeRequests().antMatchers("/api/**").hasIpAddress("dynamic List of IPs");
It should be checked whether the IP is stored in the database, otherwise the access is to be denied.
And the secound config takes care of the rest.
#EnableWebSecurity
public class AppSecurityConfig {
#Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new CustomUserDetailsService()).passwordEncoder(new Md5PasswordEncoder());
}
#Configuration
#Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.headers().disable()
.authorizeRequests().antMatchers("/api/**").hasIpAddress("dynamic List of IPs");
}
}
#Configuration
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().maximumSessions(1)
.expiredUrl("/error/expired.xhtml").and()
.invalidSessionUrl("/Anmeldung.xhtml?check=invalid");
http
.csrf().disable()
.headers().disable()
.formLogin().loginPage("/Anmeldung/").loginProcessingUrl("/j_spring_security_check").successHandler(new CustomAuthenticationSuccessHandler())
.failureUrl("/Anmeldung.xhtml?check=error").usernameParameter("j_username").passwordParameter("j_password")
.and()
.exceptionHandling().accessDeniedPage("/error/403.xhtml")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/Anmeldung.xhtml?check=logout").invalidateHttpSession(false).deleteCookies("JSESSIONID").permitAll();
ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry interceptUrlRegistry = http.authorizeRequests();
interceptUrlRegistry.antMatchers("/Administrator/*").hasAnyAuthority("ROLE_ADMIN");
interceptUrlRegistry.antMatchers("/*").hasAnyAuthority("ROLE_USER");
interceptUrlRegistry.antMatchers("/Anmeldung/index.xhtml").anonymous();
interceptUrlRegistry.antMatchers("/template/*").denyAll();
interceptUrlRegistry.antMatchers("/resources/**").permitAll();
}
}
}
Thanks for your help.
You can dynamically configure httpsecurity object inside for loop like the code referenced below.
for (Entry<String, String> entry : hasmapObject) {
String url = entry.getKey().trim();
String ips= entry.getValue().trim();
http.authorizeRequests().and().authorizeRequests().antMatchers(url).hasIpAddress(ips);
}
This worked for me. The hashmap object had the dynamic list of url's and their corresponding ips to give access.
"http.authorizeRequests().and()" this and() is needed to indent like we use in xml configuration to configure http child elements in XML.
Please let me know if this helps.

Resources