Question

I'm trying to use Spring's Security's Java configuration in a class that extends WebSecurityConfigurerAdapter. I'm using version 3.2.0.RELEASE.

In the HttpSecurity.java class there's an example as follows.

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/**").hasRole("USER").and()
            .httpBasic();
}

When I try to use this exact example in my project, the .and() method does not return an object with the .httpBasic() method on it. The HttpSecurity http object passed into the configure() method does have .httpBasic() on it.

I'm trying to understand why this canonical example does not work. This seems pretty straightforward, and I've seen code all over the web using it in this same way.

Do I have the wrong version? I see some people using the release candiates, but I thought the 3.2.0.RELEASE version was the most current (as listed here http://projects.spring.io/spring-security/).

Was it helpful?

Solution

Your code compiles just fine for me in Eclipse, using Maven, and Gradle. I'm guessing you are using IntelliJ which has a bug for handling the generic return types. In the meantime you can move the authorizeRequests() to the bottom and IntelliJ will compile the rest.

By the way I would encourage you to use the following:

protected void configure(HttpSecurity http) throws Exception {
    http
        .httpBasic()
            .and()
        .authorizeRequests()
            .anyRequest().hasRole("USER");
}

Three changes:

  • Move authorizeRequests() to the bottom to work around the IntelliJ bug
  • You can use the anyRequest() matcher instead of antMatchers("/**") This is the same thing, but increases the readability and gives you compile time checks
  • Change the formatting to match Spring Security Java Config Preview: Readability

PS: Also of note is http://youtrack.jetbrains.com/issue/IDEA-118527

OTHER TIPS

I don't know why the example is wrong, but this works.

protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic();
    http
        .authorizeRequests()
            .antMatchers("/**").hasRole("USER");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top