如何将Spring Boot配置为.war文件和安全性?

时间:2016-08-02 09:33:06

标签: java spring spring-security spring-boot

我通过SpringBootServletInitializer类启动Spring Boot应用程序,因为我想将它部署为.war文件。我不知道如何启用安全性。

public class ApplicationInitializer extends SpringBootServletInitializer {

    private static final Object[] configurations = {
            SecurityConfiguration.class,
            ApplicationInitializer.class
    };

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(configurations);
    }
}

其中SecurityConfiguration如下:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /******/
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
         /******/
    }
}

使用此配置,我得到AlreadyBuiltException:

'springSecurityFilterChain' threw exception; nested exception is org.springframework.security.config.annotation.AlreadyBuiltException: This object has already been built

3 个答案:

答案 0 :(得分:1)

使用 AuthenticationManagerBuilder 表示该类可用于配置 @Configuration @EnableWebSecurity @EnableGlobalAuthentication public class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { // } @Override protected void configure(HttpSecurity http) throws Exception { // } } 的全局实例

public loadUsers():Observable<User[]>{
    return Promise.resolve([ new User(....);]);
  }

答案 1 :(得分:0)

错误在于SecurityConfiguration而不是:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    /******/
}

应该是:

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

但我不知道为什么要这样写。 :/

答案 2 :(得分:0)

您可以像这样从应用程序pom定义中排除嵌入式tomcat工件开始:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat.embed</groupId>
                <artifactId>tomcat-embed-core</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

然后,您可以继续进行“设置”应用程序并执行以下操作:

@SpringBootApplication
public class ApplicationInitializer extends SpringBootServletInitializer
{
    
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
    {
        return application.sources(ApplicationInitializer.class);
    }

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

通过这种方式,您可以利用Spring Framework的Servlet 3.0支持,并可以在Servlet容器启动应用程序时对其进行配置。

哦...,别忘了在pom.xml中更改应用程序包装,就像这样:

<packaging>war</packaging>

出于安全性考虑...在配置类中只是@EnableWebSecurity。