如何将 Spring WebSecurityConfig 添加到现有项目

Posted

技术标签:

【中文标题】如何将 Spring WebSecurityConfig 添加到现有项目【英文标题】:How to add Spring WebSecurityConfig to an existing project 【发布时间】:2017-07-13 01:47:11 【问题描述】:

我想向现有的 spring REST api 项目添加一个简单的配置,供 WebSecurityConfigurerAdapter 进行测试。但是当 spring 启动时,它不会加载配置。也许我需要将它添加到应用程序上下文中,但我不知道该怎么做。

如果我发curl localhost:8080/ 总是得到未经授权的响应,所以我认为那是没有加载配置,为什么会这样?或者,我应该如何加载它? 在我在 github 上看到的所有多样化项目中,他们从不做特殊的事情来加载它!可能是因为它首先加载了一个嵌入的 servlet?

这是简单的网络安全配置:

@SuppressWarnings("SpringJavaAutowiringInspection")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter 

@Autowired
private UserDetailsService userDetailsService;

@Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception 
    authenticationManagerBuilder
            .userDetailsService(this.userDetailsService)
            .passwordEncoder(passwordEncoder());


@Bean
public PasswordEncoder passwordEncoder() 
    return new BCryptPasswordEncoder();


@Override
protected void configure(HttpSecurity httpSecurity) throws Exception 
    httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()
            //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

            // allow anonymous resource requests
            .antMatchers(
                    HttpMethod.GET,
                    "/",
                    "/*.html",
                    "/favicon.ico",
                    "/**/*.html",
                    "/**/*.css",
                    "/**/*.js",
                    "/**"
            ).permitAll()
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

    // disable page caching
    httpSecurity.headers().cacheControl();


这是我的应用程序

@Configuration
@EnableConfigurationProperties
@ComponentScan(basePackageClasses = SimpleCORSFilter.class)
@EnableAutoConfiguration    org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class)
@EntityScan(basePackages = "com.thing.model")
@RestController
public class Application 


    @Bean
    public FilterRegistrationBean filterRegistrationBean() 
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        registrationBean.setFilter(characterEncodingFilter);
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);
        registrationBean.setOrder(Integer.MIN_VALUE);
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
        




    public static void main(String[] args) 
                SpringApplication application = new SpringApplication(Application.class);
        SpringApplication.run(Application.class, args);
    

    @RequestMapping("/")
    public String home() 
            return "Hello World";
    

pom.xml 依赖项

       <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.geotools</groupId>
        <artifactId>gt-referencing</artifactId>
        <version>8.2</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

【问题讨论】:

【参考方案1】:

我需要将 WebSecurityConfig 添加到应用程序上下文中,在主类声明中添加这一行:

...
@Import(WebSecurityConfig.class)
public class Application   
...

我做的另一件事是将SpringBoot升级到1.4.3.RELEASE并将主应用程序放到根文件夹:

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
  </parent>

树将是,例如:

└── com
└── app
    ├── Application.java
    └── config
        └── WebSecurityConfig.java

这会自动加载子文件夹中的所有@Configuration

【讨论】:

【参考方案2】:

查看example,了解如何在 Spring 项目中启用 Web 安全性。

【讨论】:

【参考方案3】:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ClientResourceControllerTest 

以上帮助我解决了同样的问题。

【讨论】:

以上是关于如何将 Spring WebSecurityConfig 添加到现有项目的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Spring 与 JavaFX 一起使用?

spring-如何将spring源码成功导入Eclipse中

如何将 Spring Batch Cron 作业迁移到 Spring Cloud 任务

如何将spring导入到eclipse

如何将 Spring Boot 项目迁移到旧 Spring MVC 项目。面临的问题,如何在遗留 Spring MVC 项目中读取 application.properties 文件

如何使用 Spring 将依赖项注入 HttpSessionListener?