Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring web security restrict only single page

I'm using Spring web security, with the below code that restricts all pages except those listed such as resources and app.html

How can I change this to allow all pages except ones I specifically specify?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http    .authorizeRequests()
                .antMatchers("/resources/**", "/registration", "/app.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }
}

I got the code from here: https://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/ but I couldn't see an answer to my question.

Thanks

like image 977
Wayneio Avatar asked Nov 07 '22 14:11

Wayneio


1 Answers

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

This will protect your mysupersecureurl and let the other url be open (i.e. permitAll()).

Also as a bonus, you can disable csrf, if you are doing posts to other urls than the one on the mysupersecureurl. That is a option you can keep or remove.

like image 90
Andrei Sfat Avatar answered Nov 14 '22 23:11

Andrei Sfat