小编典典

在其他程序包中扩展WebSecurityConfigurerAdapter类时,自定义安全性不起作用

spring-boot

WebSecurityConfigurerAdapter除了包含的类的软件包以外,我在其他软件包中具有extendend
@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");
    }


}

阅读 839

收藏
2020-05-30

共1个答案

小编典典

@SpringBootApplication为短手@Configuration@EnableAutoConfiguration@ComponentScan。这使得Spring可以为当前的软件包以及低于此级别的软件包做组件扫描。因此,在所有类com.example和下com.example被扫描bean创建的,而不是任何其他上述com.examplecom.securitymodule

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

2020-05-30