Category Archives: Spring

Spring Security Misconfiguration

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

I recently saw Mike Wienser’s SpringOne2GX talk about Application Security Pitfalls. It is very informative and worth watching if you are using Spring’s stack on servlet container.

It reminded me one serious Spring Security Misconfiguration I was facing once. Going to explain it on Spring’s Guide Project called Securing a Web Application. This project uses Spring Boot, Spring Integration and Spring MVC.

Project uses these views:

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
    
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

Where “/home”, “/” and “/login” URLs should be publicly accessible and “/hello” should be accessible only to authenticated user. Here is original Spring Security configuration from Guide:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated();
        http
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}

Nice and explanatory as all Spring’s Guides are. First “configure” method registers “/” and “home” as public and specifies that everything else should be authenticated. It also registers login URL. Second “configure” method specifies authentication method for role “USER”. Of course you don’t want to use it like this in production :).

Now I am going to slightly amend this code.

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //!!! Don't use this example !!!
        http
            .authorizeRequests()              
                .antMatchers("/hello").hasRole("USER");
        
        //... same as above ...
    }

Everything is public and private endpoints have to be listed. You can see that my amended code have the same behavior as original. In fact it saved one line of code.

But there is serious problem with this. What if my I need to introduce new private endpoint? Let’s say I am not aware of the fact that it needs to be registered in Spring Security configuration. My new endpoint would be public. Such misconfiguration is really hard to catch and can lead to unwanted exposure of URLs.

So conclusion is: Always authenticate all endpoints by default.

twittergoogle_plusrss

Load implementors of an interface into list with Spring

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

Last week I wrote a blog post how to load complete inheritance tree of Spring beans into list. Similar feature can be used for autowiring all implementors of certain interface.

Let’s have this structure of Spring beans. Notice that Bear is abstract class, therefore it’s not a Spring bean. So we have three beas: Wolf, PolarBear and Grizzly.

implementors

Now let’s load implementors into list with constructor injection:

@Service
public class Nature {
	List<Runner> runners;

	@Autowired
	public Nature(List<Runner> runners) {
		this.runners = runners;
	}

	public void showRunners() {
		runners.forEach(System.out::println);
	}
}

Method showRunners is using Java 8 forEach method that consumes method reference.  This construct outputs loaded beans into console. You would find a lot of reading about these new Java 8 features these days.

Spring context is loaded by this main class:

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(SpringContext.class);

		Nature nature = context.getBean(Nature.class);
		nature.showRunners();
	}
}

Console output:

PolarBear []
Wolf []
Grizzly []

This feature can be handy sometimes. Source code of this short example is on Github.

twittergoogle_plusrss

Load inheritance tree into List with Spring

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

I noticed interesting Spring feature. One of my colleagues used it for loading whole inheritance tree of Spring beans into list. Missed that when I was studying Spring docs.

Let’s have this inheritance tree of Spring beans:

animals-class-diagram

Not let’s load inheritance tree of beans into list with constructor injection:

@Component
public class Nature {
	List<Animal> animals;

	@Autowired
	public Nature(List<Animal> animals) {
		this.animals = animals;
	}

	public void showAnimals() {
		animals.forEach(animal -> System.out.println(animal));
	}
}

Method showAnimals is using Java 8 lambda expression to output loaded beans into console. You would find a lot of reading about this new Java 8 feature these days.

Spring context is loaded by this main class:

public class Main {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(SpringContext.class);

		Nature nature = context.getBean(Nature.class);
		nature.showAnimals();
	}
}

Console output:

PolarBear []
Wolf []
Animal []
Grizzly []
Bear []

This feature can be handy sometimes. Source code of this short example is on Github.

twittergoogle_plusrss

Promoting constructor over field injection

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

I wrote blog post about testing field injection with Mockito (using @InjectMocks/@Mock/@Spy). It describes how to inject dependencies into testing object. But I didn’t pay attention to thinking about problems of field injection itself. Let me summarize few arguments against field injections that convinced me to treat it as bad practice:

  1. Field injection hides class dependencies. Constructor injection on the other hand exposes them. So it’s enough to look at class API.
  2. Constructor injection doesn’t allow creation of circular dependencies.
  3. Constructor injection uses standard Java features to inject dependencies. It is definitely much cleaner than field injection which involves using reflection twice under the hood:
    1. Spring must use reflection to inject private field
    2. Mockito (during the test) must use reflection to inject mocks into testing object
  4. Developer would need to create awful non-default constructor with a lot of parameters for tightly coupled class. Nobody likes huge amount of parameters. So constructor injection naturally forces him to think about decoupling and reducing dependencies for the class. This is biggest advantage of constructor injection for me.

So I am another member of Constructor injection camp now. This nice Petri Kainulainen’s blog post gathers more reading about pros and cons of both approaches.

twittergoogle_plusrss

Enterprise Integration with Spring Certification study notes and hints

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

Spring projects contain wide range of frameworks and abstraction APIs for Enterprise Integration. Best way to get an overview what Spring provides is to attend Enterprise Integration with Spring Training. It is unfortunately not affordable for everybody and I am not aware of any publication out there that explains Spring’s integration technologies altogether. Training includes:

  • Tasks and Scheduling support
  • Spring Remoting
  • Spring Web Services
  • Spring REST with Spring MVC
  • Spring JMS
  • Local and distributed transactions support
  • Spring Itegration
  • Spring Batch

I recently attended this course (thanks to my employer) and did certification exam afterwards. Now I would like to share my study notes and hints. These should provide you decent overview about Enterprise Integration with Spring. Study notes should cover everything needed for certification exam. But for passing the exam it isn’t enough just to memorize them. Unless you are familiar with these technologies already. They contain too many crucial information you can easily miss. You wouldn’t be successful until you get used each particular technology at least via examples or tutorials. I went through original SpringSource labs provided by training, few examples and tutorials. Also I was already familiar with Spring JMS, Spring MVC, Spring Integration and Spring transaction demarcation.

Study notes

  • Are based mainly on Spring reference documentations
  • Also contains some crucial principles and best practices Spring promotes that are usually not mentioned in reference documentations
  • Contains a lot of Spring XML configuration and Java code snippets
  • 57 pages
  • Download in PDF format
  • Download in ODT format (LibreOffice / OpenOffice)

Study hints, additional materials

  • Official Enterprise Integration with Spring certification study guide
  • Our training lecturer – Jorge Simao
    • provides very useful information on his site:
      • Certification reading list – [EDIT: Unfortunately reading list link was removed -> fire email to lubos.krnac@gmail.com]
    • gave us valuable advices for certification exam:
      • When there is question on what Spring supports, correct answers are often where Spring looks better.
      • Question are focused on Spring’s API and principles Spring promotes rather than underlying third party technologies.
  • Antoine Rey’s Java blog
    • Mock exam
    • Study notes
      • I was looking into these notes while I was creating mine
      • much shorter, but worth look into
      • unfortunately French only, but Google translator provides decent workaround

Examples

Suggested readings

You can schedule certification exam via Pearson VUE site, find SpringSource and your local certification center. Exam ID is SpringEIwSCertV1.0.

Hope these materials help you also gain this badge:

Enterprise Integration with Spring

twittergoogle_plusrss