Home > Blockchain >  Disable securitycontext without using depricated WebSecurityConfigurerAdapter
Disable securitycontext without using depricated WebSecurityConfigurerAdapter

Time:07-13

I'm trying to rewrite following class in order to get rid of the depricated WebSecurityConfigurerAdapter:

@EnableWebSecurity
public class MyWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity security) throws Exception {
        security.mvcMatcher("/my/path/*").securityContext().disable();
    }

}

And I've tried to rewrite this with the help of the official Spring documentation. The following two attempts resulted in 403 Errors when trying to access resources on that path:

@EnableWebSecurity
public class MyWebSecurityConfiguration {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity security) throws Exception {
        security.mvcMatcher("/my/path/*").securityContext().disable();
        return security.build();
    }
}
@EnableWebSecurity
public class ConsentWebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() throws Exception {
        return (web) ->  web.ignoring().mvcMatchers("/v1/containers/*");
    }
}

While in the original code everything is running

CodePudding user response:

I also faced the same scenario of discarding the deprecated method and replacing it with SecurityFilterChain

if you want to disable the security on given path then try this:

security.mvcMatcher("/my/path/*").permitAll();

Edit: Here is my migrated code which worked fine with permitting every request without authentication.

@Configuration
@EnableWebMvc
public class SecurityConfig {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    protected SecurityFilterChain authorizationConfig(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/login", "/post/**", "/newcomment/**", "/page/**","/api/","/api/posts/filter",
                        "/api/comments").permitAll();
        return httpSecurity.build();
    }

CodePudding user response:

You can use below code for reference

    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfiguration {
    
        private final String[] WHITE_LABEL_URLS = {"/blogapp", "/usercreation", "/css/**", "/saveuser", "/page/**"};
    
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
                    .httpBasic()
                    .and()
                    .authorizeHttpRequests()
                    .antMatchers(WHITE_LABEL_URLS).permitAll()
                    .anyRequest().authenticated()
.securityContext().disable();
    
            return httpSecurity.build();
        }
    }
  • Related