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

时间:2017-05-09 11:14:31

标签: java spring-boot

我在包含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 个答案:

答案 0 :(得分:13)

@SpringBootApplication@Configuration@EnableAutoConfiguration@ComponentScan的简写。这使得Spring可以为此下面的当前包和包执行组件扫描。因此,com.examplecom.example下的所有课程都会被扫描以创建bean,而com.example以外的任何其他课程都不会com.securitymodule

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