Custom security is not working when extending the WebSecurityConfigurerAdapter class in different package

dead programmer :

I have extendend WebSecurityConfigurerAdapter in a different package other than the package containing class for @SpringBootApplication. Then it's not working its generating default username and password.

And it's working fine when it's in the same package.

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;



@SpringBootApplication
public class DemoApplication {

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

class extending WebSecurityConfigurerAdapter

package com.securitymodule;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        super.configure(http);
        http.antMatcher("/**").authorizeRequests().anyRequest().hasRole("USER").and().formLogin();
    }


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
        .inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        super.configure(auth);
        auth.
        inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
    }


}
Praneeth Ramesh :

@SpringBootApplication is a short hand for @Configuration, @EnableAutoConfiguration, @ComponentScan. This makes Spring to do componentscan for the current packages and packages below this. So all classes in com.example and under com.example are scanned for bean creation while not any others above com.example like com.securitymodule

Hence either add @ComponentScan(basePackages = {"com.securitymodule"}) into your main class, or make the package of WebSecurityConfigurerAdapter as com.example.securitymodule

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=463602&siteId=1
Recommended