2014-11-16 136 views
1

我試圖使用Spring安全3.2.5和基於java的配置來保護REST API。 其實我發現很多用「老」xml方法開發的例子,但沒有完整的java配置。 我在哪裏可以找到一些有用的教程?春季安全3.2.5和基於令牌的認證

該項目創建了一個REST API和一些JSP usesd允許管理員來填充underlyin DB(休眠作爲ORM):

這裏是我的配置類:

package com.idk.fantappapaback.spring; 

import java.util.Properties; 

import javax.sql.DataSource; 

import org.apache.tomcat.dbcp.dbcp.BasicDataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.web.multipart.support.StandardServletMultipartResolver; import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.JstlView; import org.springframework.web.servlet.view.UrlBasedViewResolver; 

import com.google.common.base.Preconditions; import com.idk.fantappapaback.spring.security.SecurityConfig; 

@Configuration @EnableWebMvc @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql.properties" }) @ComponentScan({ "com.idk.fantappapaback.persistence","com.idk.fantappapaback.rest","com.idk.fantappapaback.spring.controllers","com.idk.fantappapaback.spring.security" }) @Import({ SecurityConfig.class }) public class BackEndConfig extends WebMvcConfigurerAdapter{ 

    @Autowired 
    private Environment env; 

    public BackEndConfig() { 
     super(); 
    } 


    //l'application context estrae il session factory da questo bean 
    @Bean 
    public LocalSessionFactoryBean sessionFactory() { 
     final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 
     sessionFactory.setDataSource(restDataSource()); 
     sessionFactory.setPackagesToScan(new String[] { "com.idk.fantappapaback.persistence.model" }); 
     sessionFactory.setHibernateProperties(hibernateProperties()); 

     return sessionFactory; 
    } 

    @Bean 
    public DataSource restDataSource() { 
     final BasicDataSource dataSource = new BasicDataSource(); 
     dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); 
     dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("jdbc.url"))); 
     dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); 
     dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); 

     return dataSource; 
    } 

    @Bean 
    @Autowired 
    public HibernateTransactionManager transactionManager(final SessionFactory sessionFactory) { 
     final HibernateTransactionManager txManager = new HibernateTransactionManager(); 
     txManager.setSessionFactory(sessionFactory); 

     return txManager; 
    } 

    @Bean 
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { 
     return new PersistenceExceptionTranslationPostProcessor(); 
    } 

    final Properties hibernateProperties() { 
     final Properties hibernateProperties = new Properties(); 
     hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); 
     hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); 

     //***Proprieta per l'output delle query in sql che qui disabilito 

     // hibernateProperties.setProperty("hibernate.show_sql", "true"); 
     // hibernateProperties.setProperty("hibernate.format_sql", "true"); 
     // hibernateProperties.setProperty("hibernate.globally_quoted_identifiers", "true"); 

     return hibernateProperties; 
    } 


    @Bean 
    public UrlBasedViewResolver setupViewResolver() { 
     UrlBasedViewResolver resolver = new UrlBasedViewResolver(); 
     resolver.setPrefix("WEB-INF/views/"); 
     resolver.setSuffix(".jsp"); 
     resolver.setViewClass(JstlView.class); 
     return resolver; 
    } 

    @Override 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
     configurer.enable(); 
    } 
    @Bean 
    public StandardServletMultipartResolver multipartResolver(){ 
     return new StandardServletMultipartResolver(); 
    } 
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
      registry.addResourceHandler("/resources/**") 
      .addResourceLocations("/resources/"); //   registry.addResourceHandler("/css/**") //   .addResourceLocations("/css/"); //  registry.addResourceHandler("/img/**") //   .addResourceLocations("/img/"); 
      registry.addResourceHandler("/js/**") 
      .addResourceLocations("/js/"); 
     } 

} 

這是我的,我使用有非常基本的安全配置表單登錄的JSP觀點:

package com.idk.fantappapaback.spring.security; 

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; 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; 


@Import({ SecurityConfig.class }) nella BackEndConfig @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ @Autowired  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("masquenada").password("123456").roles("USER"); // auth.inMemoryAuthentication().withUser("masquenada").password("123456").roles("ADMIN");  auth.inMemoryAuthentication().withUser("masquenada").password("123456").roles("SUPERADMIN"); } 



     @Override protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() //  .antMatchers("/players/**").access("hasRole('ROLE_USER')")  .antMatchers("/createSeason/**").access("hasRole('ROLE_SUPERADMIN')") .and().formLogin().permitAll()  .and().httpBasic(); 
     } } 

這裏是我的SecurityWebApplicationInitializer:

package com.idk.fantappapaback.spring.security; 

import org.springframework.security.web.context.*; 

public class SecurityWebApplicationInitializer 
     extends AbstractSecurityWebApplicationInitializer { 

} 

主要問題是:如何添加基於令牌的自動化? 我已經添加了Spring oAuth 2和Spring集成到我的pom中,但我需要一些關於引入spring oAuth來保持表單登錄的提示。

+0

當您發佈的代碼(即不工作),這將是helpeful一個很好的答案,並說明希望工作,以及代替發生什麼。 – Ralph

+0

其實我仍然在努力尋找達到我目標的最佳方式。 如果有用,我可以在我所做的事情上添加一些細節。 –

回答