Permitall only works with httpsecurity.authorizerequests()

Explanation:

The permitAll() method is used in Spring Security to indicate that any user, regardless of their authentication status, is allowed to access a specific URL or set of URLs. It configures an access rule that grants unrestricted access.

In Spring Security, the authorizeRequests() method is used to define which URLs should be secured and how they should be secured. It allows for specifying access rules based on various conditions like roles, authorities, or custom logic.

When applying the permitAll() method, it must be used in conjunction with the authorizeRequests() method. This combination allows for restricting access to certain URLs while permitting unrestricted access to others.

Here’s an example to demonstrate the usage of permitAll() and authorizeRequests():

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .antMatchers("/public/**").permitAll()
        .anyRequest().authenticated()
        .and()
      .httpBasic();
  }
}

In the above example, the permitAll() method is used to allow unrestricted access to any path starting with “/public/”. The antMatchers() method is used to specify the pattern for the URLs, and the permitAll() method is called to grant public access.

For any other URL not matching “/public/**”, authentication is required. The anyRequest().authenticated() method sets this rule. Finally, httpBasic() configures HTTP Basic authentication.

Leave a comment