2016-08-02 80 views
1

由SpringBootServletInitializer類開始我的Spring Boot應用程序,因爲我想將它部署爲.war文件。我不知道如何啓用安全性。如何將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 
+0

嘗試的全局實例加載在'application.sources只有當前類()'例如'返回application.sources(ApplicationInitializer.class);''SecurityConfiguration'將被組件掃描,如果應用程序結構正確。 –

+0

SecurityConfiguration與ApplicationInitializer在同一個包中。但是,當我只加載ApplicationInitializer時,spring安全仍然處於默認模式(基本身份驗證只有一個用戶,並且在控制檯中隨機生成密碼) –

+0

ApplicationInitializer是否具有'@ SpringBootApplication'? –

回答

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

但我不知道爲什麼這應該寫這種方式。 :/

1

使用@EnableGlobalAuthentication用於指示類可以被用來配置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 {  
     //     
    } 
}