基于java config的springSecurity(一)--基本搭建

本文主要介绍基于java config的springMvc+springDataJpa+springSecurity的基本集成配置.spring data jpa等等相关的资料在前面博文有介绍.


1.pom.xml.

[html]  view plain  copy
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0modelVersion>  
  4.     <groupId>org.examgroupId>  
  5.     <artifactId>testwebartifactId>  
  6.     <packaging>warpackaging>  
  7.     <version>1.0-SNAPSHOTversion>  
  8.     <name>Maven Webappname>  
  9.     <url>http://maven.apache.orgurl>  
  10.     <properties>  
  11.         <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>  
  12.         <slf4j.version>1.7.7slf4j.version>  
  13.         <spring.version>4.1.2.RELEASEspring.version>  
  14.         <hibernate.version>4.3.1.Finalhibernate.version>  
  15.         <spring.security.version>3.2.5.RELEASEspring.security.version>  
  16.     properties>  
  17.     <build>  
  18.   
  19.             <plugins>  
  20.                 <plugin>  
  21.                     <groupId>org.apache.maven.pluginsgroupId>  
  22.                     <artifactId>maven-compiler-pluginartifactId>  
  23.                     <configuration>  
  24.                         <source>1.7source>  
  25.                         <target>1.7target>  
  26.                     configuration>  
  27.                 plugin>  
  28.                 <plugin>  
  29.                     <groupId>org.eclipse.jettygroupId>  
  30.                     <artifactId>jetty-maven-pluginartifactId>  
  31.                     <version>9.2.2.v20140723version>  
  32.                     <configuration>  
  33.                         <webApp>  
  34.                             <contextPath>/${project.artifactId}contextPath>  
  35.                         webApp>  
  36.                         <httpConnector>  
  37.                             <port>8080port>  
  38.                             <idleTimeout>60000idleTimeout>  
  39.                         httpConnector>  
  40.                     configuration>  
  41.                 plugin>  
  42.             plugins>  
  43.   
  44.     build>  
  45.     <dependencies>  
  46.         <dependency>  
  47.             <groupId>org.slf4jgroupId>  
  48.             <artifactId>jcl-over-slf4jartifactId>  
  49.             <version>${slf4j.version}version>  
  50.         dependency>  
  51.         <dependency>  
  52.             <groupId>org.slf4jgroupId>  
  53.             <artifactId>slf4j-log4j12artifactId>  
  54.             <version>${slf4j.version}version>  
  55.         dependency>  
  56.         <dependency>  
  57.             <groupId>org.springframeworkgroupId>  
  58.             <artifactId>spring-webmvcartifactId>  
  59.             <version>${spring.version}version>  
  60.             <exclusions>  
  61.                 <exclusion>  
  62.                     <groupId>commons-logginggroupId>  
  63.                     <artifactId>commons-loggingartifactId>  
  64.                 exclusion>  
  65.             exclusions>  
  66.         dependency>  
  67.         <dependency>  
  68.             <groupId>org.springframeworkgroupId>  
  69.             <artifactId>spring-aopartifactId>  
  70.             <version>${spring.version}version>  
  71.         dependency>  
  72.         <dependency>  
  73.             <groupId>org.springframeworkgroupId>  
  74.             <artifactId>spring-ormartifactId>  
  75.             <version>${spring.version}version>  
  76.         dependency>  
  77.         <dependency>  
  78.             <groupId>org.springframeworkgroupId>  
  79.             <artifactId>spring-jdbcartifactId>  
  80.             <version>${spring.version}version>  
  81.         dependency>  
  82.         <dependency>  
  83.             <groupId>org.springframework.securitygroupId>  
  84.             <artifactId>spring-security-webartifactId>  
  85.             <version>${spring.security.version}version>  
  86.         dependency>  
  87.         <dependency>  
  88.             <groupId>org.springframework.securitygroupId>  
  89.             <artifactId>spring-security-configartifactId>  
  90.             <version>${spring.security.version}version>  
  91.         dependency>  
  92.   
  93.         <dependency>  
  94.             <groupId>org.hibernategroupId>  
  95.             <artifactId>hibernate-entitymanagerartifactId>  
  96.             <version>${hibernate.version}version>  
  97.         dependency>  
  98.         <dependency>  
  99.             <groupId>org.springframework.datagroupId>  
  100.             <artifactId>spring-data-jpaartifactId>  
  101.             <version>1.7.0.RELEASEversion>  
  102.         dependency>  
  103.         <dependency>  
  104.             <groupId>org.springframeworkgroupId>  
  105.             <artifactId>spring-testartifactId>  
  106.             <version>${spring.version}version>  
  107.             <scope>testscope>  
  108.         dependency>  
  109.         <dependency>  
  110.             <groupId>c3p0groupId>  
  111.             <artifactId>c3p0artifactId>  
  112.             <version>0.9.1.2version>  
  113.         dependency>  
  114.         <dependency>  
  115.             <groupId>mysqlgroupId>  
  116.             <artifactId>mysql-connector-javaartifactId>  
  117.             <version>5.1.26version>  
  118.         dependency>  
  119.         <dependency>  
  120.             <groupId>com.fasterxml.jackson.coregroupId>  
  121.             <artifactId>jackson-databindartifactId>  
  122.             <version>2.3.1version>  
  123.         dependency>  
  124.         <dependency>  
  125.             <groupId>javax.servletgroupId>  
  126.             <artifactId>javax.servlet-apiartifactId>  
  127.             <version>3.1.0version>  
  128.             <scope>providedscope>  
  129.         dependency>  
  130.         <dependency>  
  131.             <groupId>javax.servlet.jspgroupId>  
  132.             <artifactId>jsp-apiartifactId>  
  133.             <version>2.2.1-b03version>  
  134.             <scope>providedscope>  
  135.         dependency>  
  136.         <dependency>  
  137.             <groupId>javax.servlet.jsp.jstlgroupId>  
  138.             <artifactId>javax.servlet.jsp.jstl-apiartifactId>  
  139.             <version>1.2.1version>  
  140.             <scope>providedscope>  
  141.         dependency>  
  142.         <dependency>  
  143.             <groupId>org.apache.taglibsgroupId>  
  144.             <artifactId>taglibs-standard-implartifactId>  
  145.             <version>1.2.1version>  
  146.         dependency>  
  147.         <dependency>  
  148.             <groupId>commons-fileuploadgroupId>  
  149.             <artifactId>commons-fileuploadartifactId>  
  150.             <version>1.3.1version>  
  151.         dependency>  
  152.         <dependency>  
  153.             <groupId>junitgroupId>  
  154.             <artifactId>junitartifactId>  
  155.             <version>4.11version>  
  156.             <scope>testscope>  
  157.         dependency>  
  158.     dependencies>  
  159. project>  
2.配置
a.AppConfig:基本Bean的注册.注册数据源,Jpa实体管理工厂,事务管理器Bean.启用事务,spring data jpa的支持.

[java]  view plain  copy
  1. package org.exam.config;  
  2. import com.mchange.v2.c3p0.ComboPooledDataSource;  
  3. import org.springframework.context.annotation.Bean;  
  4. import org.springframework.context.annotation.Configuration;  
  5. import org.springframework.context.annotation.PropertySource;  
  6. import org.springframework.core.env.Environment;  
  7. import org.springframework.data.jpa.repository.config.EnableJpaRepositories;  
  8. import org.springframework.orm.jpa.JpaTransactionManager;  
  9. import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;  
  10. import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;  
  11. import org.springframework.transaction.PlatformTransactionManager;  
  12. import org.springframework.transaction.annotation.EnableTransactionManagement;  
  13. import javax.annotation.Resource;  
  14. import javax.sql.DataSource;  
  15. import java.beans.PropertyVetoException;  
  16. import java.util.Properties;  
  17. /** 
  18.  * Created by xin on 15/1/7. 
  19.  */  
  20. @Configuration  
  21. @PropertySource("classpath:config.properties")  
  22. @EnableTransactionManagement  
  23. @EnableJpaRepositories(basePackages={"org.exam.repository"})  
  24. public class AppConfig{  
  25.     @Resource  
  26.     private Environment env;  
  27.     @Bean(destroyMethod="close")  
  28.     public DataSource dataSource() {  
  29.         ComboPooledDataSource dataSource=new ComboPooledDataSource();  
  30.         try {dataSource.setDriverClass(env.getProperty("c3p0.driverClass"));} catch (PropertyVetoException e) {e.printStackTrace();}  
  31.         dataSource.setJdbcUrl(env.getProperty("c3p0.jdbcUrl"));  
  32.         dataSource.setUser(env.getProperty("c3p0.user"));  
  33.         dataSource.setPassword(env.getProperty("c3p0.password"));  
  34.         dataSource.setInitialPoolSize(Integer.valueOf(env.getProperty("c3p0.initialPoolSize")));  
  35.         dataSource.setAcquireIncrement(Integer.valueOf(env.getProperty("c3p0.acquireIncrement")));  
  36.         dataSource.setMinPoolSize(Integer.valueOf(env.getProperty("c3p0.minPoolSize")));  
  37.         dataSource.setMaxPoolSize(Integer.valueOf(env.getProperty("c3p0.maxPoolSize")));  
  38.         dataSource.setMaxIdleTime(Integer.valueOf(env.getProperty("c3p0.maxIdleTime")));  
  39.         dataSource.setIdleConnectionTestPeriod(Integer.valueOf(env.getProperty("c3p0.idleConnectionTestPeriod")));  
  40.         return dataSource;  
  41.     }  
  42.     @Bean  
  43.     public LocalContainerEntityManagerFactoryBean entityManagerFactory(){  
  44.         HibernateJpaVendorAdapter jpaVendorAdapter=new HibernateJpaVendorAdapter();  
  45.         jpaVendorAdapter.setGenerateDdl(true);  
  46.         jpaVendorAdapter.setShowSql(true);  
  47.         Properties jpaProperties=new Properties();  
  48.         jpaProperties.setProperty("hibernate.hbm2ddl.auto""update");//validate,create,create-drop  
  49.         LocalContainerEntityManagerFactoryBean emf=new LocalContainerEntityManagerFactoryBean();  
  50.         emf.setDataSource(dataSource());  
  51.         emf.setPackagesToScan("org.exam.domain");  
  52.         emf.setJpaVendorAdapter(jpaVendorAdapter);  
  53.         emf.setJpaProperties(jpaProperties);  
  54.         return emf;  
  55.     }  
  56.     @Bean  
  57.     public PlatformTransactionManager transactionManager(){  
  58.         JpaTransactionManager transactionManager=new JpaTransactionManager();  
  59.         transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());  
  60.         return transactionManager;  
  61.     }  
  62. }  
b.MvcConfig:spring mvc配置.启用Sprin gData Web支持,配置静态资源和视图解析器
[java]  view plain  copy
  1. package org.exam.config;  
  2. import org.springframework.context.annotation.Bean;  
  3. import org.springframework.context.annotation.ComponentScan;  
  4. import org.springframework.context.annotation.Configuration;  
  5. import org.springframework.data.web.config.EnableSpringDataWebSupport;  
  6. import org.springframework.http.converter.HttpMessageConverter;  
  7. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;  
  8. import org.springframework.web.multipart.MultipartResolver;  
  9. import org.springframework.web.multipart.commons.CommonsMultipartResolver;  
  10. import org.springframework.web.servlet.config.annotation.EnableWebMvc;  
  11. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;  
  12. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;  
  13. import org.springframework.web.servlet.view.InternalResourceViewResolver;  
  14. import java.util.List;  
  15. /** 
  16.  * Created by xin on 15/1/7. 
  17.  */  
  18. @Configuration  
  19. @ComponentScan(basePackages={"org.exam.web"})  
  20. @EnableWebMvc  
  21. @EnableSpringDataWebSupport  
  22. public class MvcConfig extends WebMvcConfigurerAdapter{  
  23.     @Override  
  24.     public void configureMessageConverters(List> converters) {  
  25.         converters.add(new MappingJackson2HttpMessageConverter());  
  26.     }  
  27.     @Override  
  28.     public void addResourceHandlers(ResourceHandlerRegistry registry) {  
  29.         registry.addResourceHandler("/static/**").addResourceLocations("/static/");  
  30.     }  
  31.     @Bean  
  32.     public InternalResourceViewResolver internalResourceViewResolver() {  
  33.         InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
  34.         resolver.setPrefix("/WEB-INF/");  
  35.         resolver.setSuffix(".jsp");  
  36.         return resolver;  
  37.     }  
  38.     @Bean  
  39.     public MultipartResolver multipartResolver(){  
  40.         CommonsMultipartResolver bean=new CommonsMultipartResolver();  
  41.         bean.setDefaultEncoding("UTF-8");  
  42.         bean.setMaxUploadSize(8388608);  
  43.         return bean;  
  44.     }  
  45.   
  46. }  
c.SecurityConfig:spring security的配置
[java]  view plain  copy
  1. package org.exam.config;  
  2. import org.springframework.context.annotation.Configuration;  
  3. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;  
  4. import org.springframework.security.config.annotation.web.builders.HttpSecurity;  
  5. import org.springframework.security.config.annotation.web.builders.WebSecurity;  
  6. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;  
  7. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;  
  8. /** 
  9.  * Created by xin on 15/1/7. 
  10.  */  
  11. @Configuration  
  12. @EnableWebSecurity  
  13. public class SecurityConfig extends WebSecurityConfigurerAdapter {  
  14.     @Override  
  15.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {  
  16.         //暂时使用基于内存的AuthenticationProvider  
  17.         auth.inMemoryAuthentication().withUser("username").password("password").roles("USER");  
  18.     }  
  19.     @Override  
  20.     public void configure(WebSecurity web) throws Exception {  
  21.         web.ignoring().antMatchers("/static/**");  
  22.     }  
  23.     @Override  
  24.     protected void configure(HttpSecurity http) throws Exception {  
  25.         //暂时禁用csrf,并自定义登录页和登出URL  
  26.         http.csrf().disable()  
  27.                 .authorizeRequests().anyRequest().authenticated()  
  28.                 .and().formLogin().loginPage("/login").failureUrl("/login?error").usernameParameter("username").passwordParameter("password").permitAll()  
  29.                 .and().logout().logoutUrl("/logout").permitAll();  
  30.     }  
  31. }  
d.SecurityWebApplicationInitializer:主要任务是注册springSecurityFilterChain Filter
[java]  view plain  copy
  1. package org.exam.config;  
  2. import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;  
  3. /** 
  4.  * Created by xin on 15/1/7. 
  5.  */  
  6. public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {  
  7. }  
e.DispatcherServletInitializer:主要任务是注册DispatcherServlet Servlet
[java]  view plain  copy
  1. package org.exam.config;  
  2. import org.springframework.web.filter.CharacterEncodingFilter;  
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;  
  4. import javax.servlet.FilterRegistration;  
  5. import javax.servlet.ServletContext;  
  6. import javax.servlet.ServletException;  
  7. /** 
  8.  * Created by xin on 15/1/7. 
  9.  */  
  10. public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{  
  11.     @Override  
  12.     public void onStartup(ServletContext servletContext) throws ServletException {  
  13.         super.onStartup(servletContext);  
  14.         FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding-filter", CharacterEncodingFilter.class);  
  15.         encodingFilter.setInitParameter("encoding""UTF-8");  
  16.         encodingFilter.setInitParameter("forceEncoding""true");  
  17.         encodingFilter.setAsyncSupported(true);  
  18.         encodingFilter.addMappingForUrlPatterns(nulltrue"/*");  
  19.     }  
  20.     @Override  
  21.     protected Class[] getRootConfigClasses() {  
  22.         return new Class[] {AppConfig.class,SecurityConfig.class};  
  23.     }  
  24.     @Override  
  25.     protected Class[] getServletConfigClasses() {  
  26.         return new Class[] { MvcConfig.class };  
  27.     }  
  28.     @Override  
  29.     protected String[] getServletMappings() {  
  30.         return new String[] { "/" };  
  31.     }  
  32. }  


另外:使用最小配置法FilterChainProxy的additionalFilters包含以下Filter(要注意顺序)

org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
org.springframework.security.web.context.SecurityContextPersistenceFilter
org.springframework.security.web.header.HeaderWriterFilter
org.springframework.security.web.authentication.logout.LogoutFilter
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
org.springframework.security.web.authentication.www.BasicAuthenticationFilter
org.springframework.security.web.savedrequest.RequestCacheAwareFilter
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
org.springframework.security.web.session.SessionManagementFilter
org.springframework.security.web.access.ExceptionTranslationFilter
org.springframework.security.web.access.intercept.FilterSecurityInterceptor

 
  

其中SecurityContextPersistenceFilter就是使用Session保存用户认证通过的Authentication.下面简要看看doFilter方法

[java]  view plain  copy
  1. //前面省略  
  2. HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);  
  3. SecurityContext contextBeforeChainExecution = repo.loadContext(holder);  
  4. try {  
  5.     SecurityContextHolder.setContext(contextBeforeChainExecution);  
  6.     chain.doFilter(holder.getRequest(), holder.getResponse());  
  7. finally {  
  8.     SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext();  
  9.     // Crucial removal of SecurityContextHolder contents - do this before anything else.  
  10.     SecurityContextHolder.clearContext();  
  11.     repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());  
  12.     request.removeAttribute(FILTER_APPLIED);  
  13.     if (debug) {  
  14.     logger.debug("SecurityContextHolder now cleared, as request processing completed");  
  15.     }  
  16. }  
其中repo就是初始化spring容器时通过构造方法注入的HttpSessionSecurityContextRepository
repo.loadContext(holder);就是从session获得有关的认证上下文.
repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse());就是将有关的认证上下文保存在session里面


源码:http://download.csdn.net/detail/xiejx618/8349559

你可能感兴趣的:(JAVA)