9

I have a spring security config method. I want a particular method to be chained antMatchers("/**/**").permitAll() only if a condition matches. something like this {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} . Ofcourse it's not a valid syntax , what is the MOST CONSISE way of doing it . Looking for a menimum coding .

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().disable()
            .authorizeRequests()
            {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} //dev only. NEVER enable on prod 
                .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/api/signin")
                .successHandler(authSuccessHandler())
                .failureHandler(authFailureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
sapy
  • 8,952
  • 7
  • 49
  • 60

2 Answers2

8

The only way is to assign the intermediate object to a variable.

WhateverAuthorizeRequestsReturns partial = http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests();

if (dev) // note: you don't need 'dev == true' like you had
{
    partial.someOptionalThing();
    // if the type is immutable then you need to reassign e.g.:
    // partial = partial.someOptionalThing()
}

partial.something()
    .somethingElse()
    .andTheRest();
Michael
  • 41,989
  • 11
  • 82
  • 128
  • Hmm.Good one. Let me wait for somebody if they can come up with an inline version of this. – sapy Jan 11 '19 at 18:56
4

if all you want to do is to allow access to certain path based on a boolean value, you can try this :

 http
        .csrf().disable()
        .cors().disable()
        .authorizeRequests()
        .antMatchers(dev ? "/**/**":"invalid-path").permitAll()
            .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/")
            .loginProcessingUrl("/api/signin")
            .successHandler(authSuccessHandler())
            .failureHandler(authFailureHandler())
            .permitAll()
            .and()
        .logout()
            .permitAll();
Reza Nasiri
  • 1,360
  • 1
  • 6
  • 19