Rocky Inde
Rocky Inde

Reputation: 1531

Unable to override spring boot's (default) security configuration

I am trying to secure a Spring boot REST application using Spring security for basic authentication.

The default basic authentication works by simply plugging in the following dependency

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

The next step is to override the default authentication credentials provided by Spring boot with some custom credentials (username, password).

I have tried this using:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    @Autowired
    public void configure (AuthenticationManagerBuilder authBuilder) throws Exception {

        authBuilder.inMemoryAuthentication()
            .withUser("aide").password("aide").roles("USER").and()
            .withUser("pervacio").password("pervacio").roles("ADMIN");
    }

    @Override
    @Autowired
    protected void configure (HttpSecurity http) throws Exception {

        http.httpBasic().and()
            .authorizeRequests()
                .antMatchers(HttpMethod.POST, "/search").hasRole("ADMIN")
            .and().csrf().disable();
    }
}

Here is my Controller:

@RestController
@SpringBootApplication
public class Controller {

    // request mappings and other code here

    public static void main(String[] args) {
        SpringApplication.run(Controller.class, args);
    }
}

The problem that I am having is that I am unable to override the default credentials with custom ones.

How do I do this?

Other posts on SO suggest annotating the configure methods with Autowired, and that isn't working for me.

What am I doing wrong? I tried the above approach by following the official example.

Upvotes: 0

Views: 1715

Answers (1)

Rocky Inde
Rocky Inde

Reputation: 1531

The problem I realized was with the location (or package) of the SecurityConfiguration.

@ComponentScan annotation (included as part of @SpringBootApplication) by default scans for components in the same package where it was defined.

Hence, there are two solutions: a) move the configuration to the same package where the annotation was defined b) configure the annotation to scan for components in the package where you placed your configuration

In my case, SecurityConfiguration file above was in a different package as compared with my application class.

Solution a:

Include the following annotation:

@ComponentScan({"<security-package-name>"})

and plug in the name of the package that has your security configuration.

Solution b:

Move the Java configuration class into the same package as that of the application class.

Upvotes: 1

Related Questions