在不同的包中扩展 WebSecurityConfigurerAdapter 类时,自定义安全性不起作用

2022-09-04 06:37:13

我在包含类的包以外的其他包中扩展了。然后它不起作用,它生成默认用户名和密码。WebSecurityConfigurerAdapter@SpringBootApplication

当它在同一个包装中时,它工作正常。

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);
    }
}

类扩展 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");
    }


}

答案 1

@SpringBootApplication是 、 、 的简写。这使得Spring做组件可以为当前的包和下面的包。因此,扫描其中和下面的所有类以创建豆类,而上面的其他类则不然。@Configuration@EnableAutoConfiguration@ComponentScancom.examplecom.examplecom.examplecom.securitymodule

因此,要么添加到您的主类中,要么将包设置为@ComponentScan(basePackages = {"com.securitymodule"})WebSecurityConfigurerAdaptercom.example.securitymodule


答案 2

推荐