2014-06-05 35 views
6

Sto cercando di utilizzare Spring Security nel mio progetto Spring-Boot.Configurazione Spring-Boot e Spring-Security

La mia struttura del progetto è:

/project 
-/src/main 
-- /java 
--/resources 
--- /static 
    ---- /css 
    ---- /fonts 
    ---- /libs 
--- /templates 
    ---- /all html files 

Ecco le mie impostazioni Gradle:

apply plugin: 'java' 
apply plugin: 'groovy' 
apply plugin: 'idea' 
apply plugin: 'spring-boot' 
apply plugin: 'jacoco' 
apply plugin: 'war' 
apply plugin: 'maven' 

project.ext { 
    springBootVersion = '1.0.2.RELEASE' 
} 

dependencies { 
    compile("org.springframework.boot:spring-boot-starter-web:$springBootVersion") 
    compile("org.springframework.boot:spring-boot:1.0.1.RELEASE") 
    compile("org.springframework.boot:spring-boot-starter-thymeleaf") 
    compile("org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion") 
    compile("org.springframework.security:spring-security-web:4.0.0.M1") 
    compile("org.springframework.security:spring-security-config:4.0.0.M1") 
... 
} 

Ognuno dei miei file html ha questo:

<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/> 
    <meta name="description" content=""/> 

    <link href="/css/bootstrap.css" rel="stylesheet"/> 
    <link href="/css/bootstrap.min.css" rel="stylesheet"/> 
    <link href="/css/bootstrap-responsive.css" rel="stylesheet"/> 
    <link href="/css/bootstrap-responsive.min.css" rel="stylesheet"/> 
    <link href="/css/ofac.css" rel="stylesheet"/> 
    <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"/> 

    <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> 
    <!--[if lt IE 9]> 
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> 
    <![endif]--> 
</head> 

Ecco il mio MVC Config: @Configuration public class MvcConfig estende WebMvcConfigurerAd Apter {

@Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
     registry.addViewController("/home").setViewName("index"); 
     registry.addViewController("/").setViewName("index"); 
     registry.addViewController("/about").setViewName("about"); 
     registry.addViewController("/login").setViewName("login"); 
     registry.addViewController("/upload").setViewName("upload"); 
     registry.addViewController("/status").setViewName("status"); 
     registry.addViewController("/search").setViewName("search"); 
    } 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
     LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); 
     localeChangeInterceptor.setParamName("lang"); 
     registry.addInterceptor(localeChangeInterceptor); 
    } 

    @Bean 
    public LocaleResolver localeResolver() { 
     CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver(); 
     cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en")); 
     return cookieLocaleResolver; 
    } 

    @Bean 
    public MessageSource messageSource() { 
     ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
     messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation"); 
     // if true, the key of the message will be displayed if the key is not 
     // found, instead of throwing a NoSuchMessageException 
     messageSource.setUseCodeAsDefaultMessage(true); 
     messageSource.setDefaultEncoding("UTF-8"); 
     // # -1 : never reload, 0 always reload 
     messageSource.setCacheSeconds(0); 
     return messageSource; 
    } 

Sulla base di diversi esempi che ho trovato on-line, ho la seguente configurazione di sicurezza:

@Configuration 
@EnableWebMvcSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private DataSource datasource; 

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

     http 
       .authorizeRequests() 
       .antMatchers("/resources/**").permitAll(); 

     http 
       .formLogin().failureUrl("/login?error") 
       .defaultSuccessUrl("/") 
       .loginPage("/login") 
       .permitAll() 
       .and() 
       .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login") 
       .permitAll(); 

     http 
       .authorizeRequests().anyRequest().authenticated(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     JdbcUserDetailsManager userDetailsService = new JdbcUserDetailsManager(); 
     userDetailsService.setDataSource(datasource); 
     PasswordEncoder encoder = new BCryptPasswordEncoder(); 

     auth.userDetailsService(userDetailsService).passwordEncoder(encoder); 
     auth.jdbcAuthentication().dataSource(datasource); 

     if (!userDetailsService.userExists("user")) { 
      List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); 
      authorities.add(new SimpleGrantedAuthority("USER")); 
      User userDetails = new User("user", encoder.encode("password"), authorities); 

      userDetailsService.createUser(userDetails); 
     } 
    } 
} 

Se navigando nelle localhost:9001 mi viene richiesto con la mia pagina di login. Fornisco le credenziali corrette e sono reindirizzato all'URL: http://localhost:9001/css/ofac.css vengono visualizzati i contenuti del mio file css. Prima di aggiungere la sicurezza, le pagine venivano visualizzate correttamente. Una volta che il login ha avuto successo, viene mostrato il css, ma se si naviga nella radice in "/" allora tutto si comporta come dovrebbe.

Qualcuno può vedere cosa sto facendo male qui?

Aggiornamento: ho tolto il seguente perché la primavera-boot gestirà i/risorse/**

http 
        .authorizeRequests() 
        .antMatchers("/resources/**").permitAll(); 

Ho cambiato anche il reindirizzamento per il login di successo:

.defaultSuccessUrl("/home")  

perché che è anche mappato a "/"

Tuttavia, il comportamento è lo stesso. Un comportamento interessante è che quando uso Safari, il login mi darà "http://localhost:9001/css/bootstrap.css", ma Firefox mi darà "http://localhost:9001/css/bootstrap-responsive.min.css"

Quando ho ispezionare il POST http://localhost:9001/login con Firebug ottengo "302 Found" seguita da un GET http://localhost:9001/css/bootstrap-responsive.min.css che restituisce un 200.

+1

'/ css' è protetto in modo non appena è richiesta per tale URL di login viene mostrato dopo il login sarete reindirizzati all'URL che ha attivato l'accesso. Mi aspetterei che il tuo css fosse disponibile in '/ resources/**' else include '/ css/**' con un 'permitAll()'. –

+0

I miei file/css sono sotto/risorse (aggiornamento post originale aggiornato per mostrare questo) quindi credo che sarebbe esposto con il mio ".authorizeRequests() .antMatchers ("/ resources/**") .permitAll(); " – sonoerin

+0

A quanto pare qualcosa sta richiedendo un css non da quella directory controlla i tuoi modelli. –

risposta

6

aggiungere questo metodo per SecurityConfig

@Override 
public void configure(WebSecurity security){ 
    security.ignoring().antMatchers("/css/**","/fonts/**","/libs/**""); 
} 
+1

Sembra che Spring Boot Security ignorerà solo auth per /css/**,,/images/** e and/js/**. Ho dovuto aggiungere manualmente la voce '/ fonts/**'. –

+0

Sì, ho dovuto fare il simile (css, js andava bene, ma non i font) ... .antMatchers ("/", "/ login **", "/ webjars/**", "/ fonts/* * "). allowAll() –

+0

come possiamo ignorare questi percorsi in Interceptor? anche se sto usando excludePathpattern ("/ css") per ignorare i percorsi di contenuto statici –

0

ho anche sperimentato la sicurezza Primavera bloccando risorse dal/static/fonts/percorso. Tuttavia, "/ static/css", "/ static/js", "/ static/images" erano consentiti per impostazione predefinita, ma/static/fonts/** era bloccato.

Di seguito è riportato un esempio di come l'ho risolto.

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 
..... 
    @Override 
    protected void configure(final HttpSecurity http) throws Exception { 
     http.authorizeRequests().antMatchers("/fonts/**").permitAll(). 
     //other security configuration rules 
    } 
..... 
} 
Problemi correlati