Application.java 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. package cn.com.taiji;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.Collection;
  7. import java.util.HashSet;
  8. import java.util.List;
  9. import java.util.Map;
  10. import java.util.concurrent.ThreadPoolExecutor;
  11. import javax.inject.Inject;
  12. import javax.servlet.MultipartConfigElement;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.sql.DataSource;
  16. import org.activiti.engine.ProcessEngine;
  17. import org.activiti.engine.ProcessEngines;
  18. import org.activiti.engine.RepositoryService;
  19. import org.activiti.engine.repository.Deployment;
  20. import org.springframework.beans.factory.annotation.Autowired;
  21. import org.springframework.beans.factory.annotation.Value;
  22. import org.springframework.boot.Banner;
  23. import org.springframework.boot.CommandLineRunner;
  24. import org.springframework.boot.SpringApplication;
  25. import org.springframework.boot.autoconfigure.AutoConfigureAfter;
  26. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  27. import org.springframework.boot.autoconfigure.SpringBootApplication;
  28. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  29. import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration;
  30. import org.springframework.boot.autoconfigure.web.MultipartProperties;
  31. import org.springframework.boot.web.servlet.FilterRegistrationBean;
  32. import org.springframework.boot.web.servlet.ServletRegistrationBean;
  33. import org.springframework.context.annotation.Bean;
  34. import org.springframework.context.annotation.Configuration;
  35. import org.springframework.context.annotation.Primary;
  36. import org.springframework.core.Ordered;
  37. import org.springframework.core.annotation.Order;
  38. import org.springframework.core.task.SimpleAsyncTaskExecutor;
  39. import org.springframework.core.task.TaskExecutor;
  40. import org.springframework.http.MediaType;
  41. import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
  42. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  43. import org.springframework.security.authentication.AuthenticationManager;
  44. import org.springframework.security.authentication.AuthenticationProvider;
  45. import org.springframework.security.authentication.ProviderManager;
  46. import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
  47. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  48. import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
  49. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  50. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  51. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  52. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  53. import org.springframework.security.config.http.SessionCreationPolicy;
  54. import org.springframework.security.core.session.SessionRegistry;
  55. import org.springframework.security.core.session.SessionRegistryImpl;
  56. import org.springframework.security.web.access.channel.ChannelProcessingFilter;
  57. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  58. //import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
  59. import org.springframework.transaction.annotation.EnableTransactionManagement;
  60. import org.springframework.web.accept.ContentNegotiationManager;
  61. import org.springframework.web.filter.CharacterEncodingFilter;
  62. import org.springframework.web.multipart.support.StandardServletMultipartResolver;
  63. import org.springframework.web.servlet.View;
  64. import org.springframework.web.servlet.ViewResolver;
  65. import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
  66. import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
  67. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  68. import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
  69. import org.springframework.web.servlet.view.json.MappingJackson2JsonView;
  70. import org.thymeleaf.dialect.IDialect;
  71. import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
  72. import org.thymeleaf.spring4.view.ThymeleafViewResolver;
  73. import com.alibaba.druid.pool.DruidDataSource;
  74. import com.alibaba.druid.support.http.StatViewServlet;
  75. import com.alibaba.druid.support.http.WebStatFilter;
  76. import com.fasterxml.jackson.databind.ObjectMapper;
  77. import com.fasterxml.jackson.databind.SerializationFeature;
  78. import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
  79. import com.fasterxml.jackson.datatype.joda.JodaModule;
  80. import cn.com.taiji.safety.RefererFilter;
  81. import cn.com.taiji.safety.permission.PermissionFilter;
  82. import cn.com.taiji.safety.xss.XssFilter;
  83. import cn.com.taiji.security.MyAuthenticationProvider;
  84. import cn.com.taiji.security.MyFailureHandler;
  85. import cn.com.taiji.security.MyFilterSecurityInterceptor;
  86. import cn.com.taiji.security.MySecurityMetadataSource;
  87. import cn.com.taiji.security.MySuccessHandler;
  88. import cn.com.taiji.security.MyUserDetailServiceImpl;
  89. import cn.com.taiji.security.MyUsernamePasswordAuthenticationFilter;
  90. import cn.com.taiji.sys.json.SysModule;
  91. import cn.com.taiji.sys.service.LoadingCacheService;
  92. import cn.com.taiji.sys.service.MenuService;
  93. import cn.com.taiji.sys.service.RoleService;
  94. import cn.com.taiji.sys.service.UserService;
  95. @EnableTransactionManagement // 开始事务管理配置
  96. @SpringBootApplication
  97. //@EnableRedisHttpSession
  98. @EnableWebSecurity
  99. @EnableGlobalMethodSecurity(securedEnabled = true)
  100. @AutoConfigureAfter(JacksonAutoConfiguration.class)
  101. @EnableAutoConfiguration(exclude = { org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
  102. org.activiti.spring.boot.SecurityAutoConfiguration.class,
  103. org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration.class })
  104. /**
  105. *
  106. * @ClassName: Application
  107. * @Description: 工程配置类
  108. * @author lijiezhi_pc
  109. * @date 2017年11月22日 下午3:45:29
  110. *
  111. */
  112. public class Application extends WebMvcConfigurerAdapter implements CommandLineRunner {
  113. /*
  114. * Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException:
  115. * No qualifying bean of type [org.springframework.core.task.TaskExecutor] is
  116. * defined: expected single matching bean but found 4:
  117. * clientInboundChannelExecutor, clientOutboundChannelExecutor,
  118. * brokerChannelExecutor, messageBrokerTaskScheduler 解决springboot 集成websocket报错
  119. */
  120. @Bean
  121. public TaskExecutor taskExecutor() {
  122. return new SimpleAsyncTaskExecutor();
  123. }
  124. static {
  125. System.setProperty("jasypt.encryptor.password", "123456");
  126. }
  127. @Override
  128. public void run(String... strings) throws Exception {
  129. // String basePath = "/Users/hujie/Documents/dev/git-repo/taiji/tianjin-cgw/zyml/cn.com.taiji.system/src/main/resources/static/diagrams";
  130. //// 1、创建ProcessEngine
  131. // ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
  132. //// 2、得到RepositoryService实例
  133. // RepositoryService repositoryService = processEngine.getRepositoryService();
  134. //// 3、使用RepositoryService进行部署
  135. // Deployment deployment = repositoryService.createDeployment()
  136. // .addInputStream("dataPreparation.bpmn", new FileInputStream(new File(basePath + "/dataPreparation.bpmn")))
  137. // .addInputStream("dataPreparation.png", new FileInputStream(new File(basePath + "/dataPreparation.png")))
  138. // .name("dataPreparation")
  139. // .deploy();
  140. // deployment = repositoryService.createDeployment()
  141. // .addInputStream("fwSq.bpmn", new FileInputStream(new File(basePath + "/fwSq.bpmn")))
  142. // .addInputStream("fwSq.png", new FileInputStream(new File(basePath + "/fwSq.png")))
  143. // .name("服务申请")
  144. // .deploy();
  145. // deployment = repositoryService.createDeployment()
  146. // .addInputStream("fwZc.bpmn", new FileInputStream(new File(basePath + "/fwZc.bpmn")))
  147. // .addInputStream("fwZc.png", new FileInputStream(new File(basePath + "/fwZc.png")))
  148. // .name("服务注册")
  149. // .deploy();
  150. // deployment = repositoryService.createDeployment()
  151. // .addInputStream("infoClassZc.bpmn", new FileInputStream(new File(basePath + "/infoClassZc.bpmn")))
  152. // .addInputStream("infoClassZc.png", new FileInputStream(new File(basePath + "/infoClassZc.png")))
  153. // .name("信息类注册")
  154. // .deploy();
  155. // deployment = repositoryService.createDeployment()
  156. // .addInputStream("requireInfo.bpmn", new FileInputStream(new File(basePath + "/requireInfo.bpmn")))
  157. // .addInputStream("requireInfo.png", new FileInputStream(new File(basePath + "/requireInfo.png")))
  158. // .name("requireInfo")
  159. // .deploy();
  160. // deployment = repositoryService.createDeployment()
  161. // .addInputStream("shareApply.bpmn", new FileInputStream(new File(basePath + "/shareApply.bpmn")))
  162. // .addInputStream("shareApply.png", new FileInputStream(new File(basePath + "/shareApply.png")))
  163. // .name("信息类共享")
  164. // .deploy();
  165. }
  166. @Bean
  167. public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
  168. ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  169. executor.setCorePoolSize(20);
  170. executor.setMaxPoolSize(100);
  171. executor.setQueueCapacity(8);
  172. executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 对拒绝task的处理策略
  173. executor.setKeepAliveSeconds(60);
  174. executor.initialize();
  175. return executor;
  176. }
  177. @Bean
  178. public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
  179. MappingJackson2HttpMessageConverter reg = new MappingJackson2HttpMessageConverter();
  180. List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
  181. supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  182. supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
  183. supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
  184. supportedMediaTypes.add(MediaType.TEXT_PLAIN);
  185. reg.setSupportedMediaTypes(supportedMediaTypes);
  186. return reg;
  187. }
  188. @Bean
  189. public ServletRegistrationBean druidServlet() {
  190. ServletRegistrationBean reg = new ServletRegistrationBean();
  191. reg.setServlet(new StatViewServlet());
  192. reg.addUrlMappings("/druid/*");
  193. reg.addInitParameter("loginUsername", "admin");
  194. reg.addInitParameter("loginPassword", "Huawei@123");
  195. return reg;
  196. }
  197. @Bean
  198. @Primary
  199. public DataSource druidDataSource(@Value("${spring.datasource.driverClassName}") String driver,
  200. @Value("${spring.datasource.url}") String url, @Value("${spring.datasource.username}") String username,
  201. @Value("${spring.datasource.password}") String password) {
  202. DruidDataSource druidDataSource = new DruidDataSource();
  203. druidDataSource.setDriverClassName(driver);
  204. druidDataSource.setUrl(url);
  205. druidDataSource.setDbType("postgresql");
  206. druidDataSource.setUsername(username);
  207. druidDataSource.setPassword(password);
  208. druidDataSource.setInitialSize(10);
  209. druidDataSource.setMinIdle(5);
  210. druidDataSource.setMaxActive(800);
  211. druidDataSource.setMaxWait(60000);// 4秒
  212. druidDataSource.setKeepAlive(true);
  213. druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
  214. druidDataSource.setMinEvictableIdleTimeMillis(300000);
  215. druidDataSource.setValidationQuery("select 1 ");
  216. druidDataSource.setTestWhileIdle(true);
  217. druidDataSource.setTestOnBorrow(true);
  218. druidDataSource.setRemoveAbandoned(true);
  219. druidDataSource.setRemoveAbandonedTimeout(1800);
  220. druidDataSource.setLogAbandoned(true);
  221. druidDataSource.setTestOnReturn(true);
  222. druidDataSource.setPoolPreparedStatements(true);
  223. druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
  224. try {
  225. druidDataSource.setFilters("stat, wall");
  226. } catch (SQLException e) {
  227. e.printStackTrace();
  228. }
  229. return druidDataSource;
  230. }
  231. // @Bean(name = "secondaryDataSource")
  232. // @Qualifier("secondaryDataSource")
  233. // public DataSource secondaryDataSource(@Value("${spring.datasource2.driverClassName}") String driver,
  234. // @Value("${spring.datasource2.url}") String url,
  235. // @Value("${spring.datasource2.username}") String username,
  236. // @Value("${spring.datasource2.password}") String password) {
  237. // DruidDataSource druidDataSource = new DruidDataSource();
  238. // druidDataSource.setDriverClassName(driver);
  239. // druidDataSource.setUrl(url);
  240. // druidDataSource.setUsername(username);
  241. // druidDataSource.setPassword(password);
  242. // druidDataSource.setInitialSize(100);
  243. // druidDataSource.setMinIdle(10);
  244. // druidDataSource.setMaxActive(400);
  245. // druidDataSource.setMaxWait(6000);
  246. // druidDataSource.setTimeBetweenEvictionRunsMillis(60000);
  247. // druidDataSource.setMinEvictableIdleTimeMillis(300000);
  248. // druidDataSource.setValidationQuery(" select 1 from dual");
  249. // druidDataSource.setTestWhileIdle(true);
  250. // druidDataSource.setTestOnBorrow(true);
  251. // druidDataSource.setRemoveAbandoned(true);
  252. // druidDataSource.setRemoveAbandonedTimeout(18000);
  253. // druidDataSource.setLogAbandoned(true);
  254. // druidDataSource.setTestOnReturn(false);
  255. // druidDataSource.setPoolPreparedStatements(true);
  256. // druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
  257. // try {
  258. // druidDataSource.setFilters("stat, wall");
  259. // } catch (SQLException e) {
  260. // e.printStackTrace();
  261. // }
  262. // return druidDataSource;
  263. // }
  264. @Bean
  265. public SessionRegistry sessionRegistry() {
  266. SessionRegistry sessionRegistry = new SessionRegistryImpl();
  267. return sessionRegistry;
  268. }
  269. @Bean
  270. public MySessionControlStrategy concurrentSessionControlStrategy() {
  271. MySessionControlStrategy concurrentSessionControlStrategy = new MySessionControlStrategy(sessionRegistry());
  272. return concurrentSessionControlStrategy;
  273. }
  274. @Bean
  275. public FilterRegistrationBean filterRegistrationBean() {
  276. FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
  277. filterRegistrationBean.setFilter(new WebStatFilter());
  278. filterRegistrationBean.addUrlPatterns("/*");
  279. filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
  280. return filterRegistrationBean;
  281. }
  282. @Bean
  283. public FilterRegistrationBean encodeRegistrationBean() {
  284. CharacterEncodingFilter encodeFilter = new CharacterEncodingFilter();
  285. encodeFilter.setEncoding("UTF-8");
  286. encodeFilter.setForceEncoding(true);
  287. FilterRegistrationBean registrationBean = new FilterRegistrationBean();
  288. registrationBean.setFilter(encodeFilter);
  289. registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE);
  290. return registrationBean;
  291. }
  292. public static void main(String[] args) {
  293. SpringApplication app = new SpringApplication(Application.class);
  294. app.setBannerMode(Banner.Mode.OFF);
  295. app.run(args);
  296. }
  297. @Bean
  298. public ObjectMapper jacksonObjectMapper() {
  299. return new ObjectMapper().registerModule(new JodaModule()).disable(SerializationFeature.FAIL_ON_EMPTY_BEANS)
  300. .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
  301. .configure(SerializationFeature.INDENT_OUTPUT, true).setDateFormat(new ISO8601DateFormat())
  302. .registerModule(new SysModule());
  303. }
  304. @Bean
  305. public MappingJackson2JsonView mappingJackson2JsonView() {
  306. MappingJackson2JsonView v = new org.springframework.web.servlet.view.json.MappingJackson2JsonView();
  307. v.setObjectMapper(jacksonObjectMapper());
  308. v.setPrettyPrint(true);
  309. return v;
  310. }
  311. protected class MappingJackson2JsonpView extends MappingJackson2JsonView {
  312. public static final String DEFAULT_CONTENT_TYPE = "application/javascript";
  313. @Override
  314. public String getContentType() {
  315. return DEFAULT_CONTENT_TYPE;
  316. }
  317. @Override
  318. public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
  319. throws Exception {
  320. Map<String, String[]> params = request.getParameterMap();
  321. if (params.containsKey("callback")) {
  322. response.getOutputStream().write(new String(params.get("callback")[0] + "(").getBytes());
  323. super.render(model, request, response);
  324. response.getOutputStream().write(new String(");").getBytes());
  325. response.setContentType(DEFAULT_CONTENT_TYPE);
  326. } else {
  327. super.render(model, request, response);
  328. }
  329. }
  330. }
  331. @Bean
  332. public MappingJackson2JsonpView mappingJackson2JsonpView() {
  333. MappingJackson2JsonpView v = new MappingJackson2JsonpView();
  334. v.setObjectMapper(jacksonObjectMapper());
  335. v.setPrettyPrint(false);
  336. return v;
  337. }
  338. @Autowired
  339. ThymeleafViewResolver thymeleafViewResolver;
  340. @Override
  341. public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
  342. configurer.favorParameter(true).ignoreAcceptHeader(false).defaultContentType(MediaType.TEXT_HTML)
  343. .mediaType("json", MediaType.APPLICATION_JSON)
  344. .mediaType("jsonp", MediaType.valueOf("application/javascript"));
  345. }
  346. @Bean
  347. public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
  348. List<ViewResolver> resolvers = new ArrayList<ViewResolver>();
  349. thymeleafViewResolver.setCache(false);
  350. // thymeleafViewResolver.setOrder(1);
  351. resolvers.add(thymeleafViewResolver);
  352. // InternalResourceViewResolver r2 = new InternalResourceViewResolver();
  353. // r2.setPrefix("templates");
  354. // r2.setSuffix(".jsp");
  355. // resolvers.add(r2);
  356. ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
  357. resolver.setViewResolvers(resolvers);
  358. resolver.setContentNegotiationManager(manager);
  359. List<View> views = new ArrayList<View>();
  360. views.add(mappingJackson2JsonView());
  361. views.add(mappingJackson2JsonpView());
  362. resolver.setDefaultViews(views);
  363. return resolver;
  364. }
  365. // see
  366. // org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration.ThymeleafDefaultConfiguration
  367. @Bean
  368. public Collection<IDialect> dialects() {
  369. Collection<IDialect> dialects = new HashSet<IDialect>();
  370. dialects.add(new SpringSecurityDialect());
  371. return dialects;
  372. }
  373. public void addViewControllers(ViewControllerRegistry registry) {
  374. registry.addViewController("/zcgllogin").setViewName("login");
  375. }
  376. @Order(Ordered.HIGHEST_PRECEDENCE)
  377. @Configuration
  378. protected static class AuthenticationSecurity extends GlobalAuthenticationConfigurerAdapter {
  379. // @Value("${spring.datasource.url}")
  380. // private String url;
  381. // @Autowired
  382. // private JdbcTemplate jt;
  383. //
  384. @Autowired
  385. private DataSource dataSource;
  386. @Autowired
  387. private SessionRegistry sessionRegistry;
  388. @Bean
  389. public ShaPasswordEncoder passwordEncoder() {
  390. // return new BCryptPasswordEncoder();
  391. return new ShaPasswordEncoder(1);
  392. }
  393. // @Autowired
  394. // public TaijiAuthenticationProvider customAuthenticationProvider;
  395. @Inject
  396. public MyUserDetailServiceImpl userDetailsService;
  397. @Override
  398. public void init(AuthenticationManagerBuilder auth) throws Exception {
  399. auth.userDetailsService(userDetailsService);
  400. // auth.authenticationProvider(customAuthenticationProvider);
  401. // @formatter:off
  402. // auth.jdbcAuthentication()
  403. // .dataSource(dataSource)
  404. // .passwordEncoder(passwordEncoder())
  405. // .groupAuthoritiesByUsername(
  406. // "select g.code, g.name, ga.role_code from user_group g, user_account_group
  407. // gm, user_group_role ga where gm.user_code = ? and g.code = ga.group_code and
  408. // g.code = gm.group_code and g.enabled = true")
  409. // .authoritiesByUsernameQuery(
  410. // "select x.user_code, x.role_code from user_account_role x, user_role r where
  411. // x.role_code=r.code and r.enabled = true and x.user_code=?")
  412. // .usersByUsernameQuery(
  413. // "select code, password, enabled from user_account where code=? and enabled =
  414. // true");
  415. // @formatter:off
  416. // auth.inMemoryAuthentication().withUser("admin").password("admin")
  417. // .roles("ADMIN", "USER").and().withUser("user")
  418. // .password("user").roles("USER");
  419. // @formatter:on
  420. }
  421. }
  422. @Autowired
  423. private MultipartProperties multipartProperties = new MultipartProperties();
  424. @Bean
  425. @ConditionalOnMissingBean
  426. public MultipartConfigElement multipartConfigElement() {
  427. this.multipartProperties.setMaxFileSize("-1");
  428. this.multipartProperties.setMaxRequestSize("-1");
  429. return this.multipartProperties.createMultipartConfig();
  430. }
  431. @Bean
  432. @ConditionalOnMissingBean
  433. public StandardServletMultipartResolver multipartResolver() {
  434. return new StandardServletMultipartResolver();
  435. }
  436. @Order(Ordered.LOWEST_PRECEDENCE - 8)
  437. protected static class ApplicationSecurity extends WebSecurityConfigurerAdapter {
  438. @Autowired
  439. private LoadingCacheService loadingCacheService;
  440. @Autowired
  441. private UserService userService;
  442. @Autowired
  443. private MySessionControlStrategy concurrentSessionControlStrategy;
  444. @Value("${pwd.invaliddays}")
  445. public int invaliddays;
  446. @Value("${pwd.invalid}")
  447. public boolean invalid;
  448. @Value("${concurrency.control}")
  449. public boolean concurrencyControl;
  450. @Value("${concurrency.limit}")
  451. public int concurrencyLimit;
  452. @Value("${concurrency.priority}")
  453. public int concurrencyPriority;
  454. @Value("${concurrency.hour_start}")
  455. public int concurrencyHourStart;
  456. @Value("${concurrency.hour_end}")
  457. public int concurrencyHourEnd;
  458. @Inject
  459. SessionRegistryImpl sessionRegistryImpl;
  460. @Bean
  461. public MyUsernamePasswordAuthenticationFilter loginFilter() throws Exception {
  462. MyUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter = new MyUsernamePasswordAuthenticationFilter();
  463. customUsernamePasswordAuthenticationFilter.setAuthenticationSuccessHandler(customSuccessHandler());
  464. customUsernamePasswordAuthenticationFilter.setAuthenticationFailureHandler(customFailureHandler());
  465. customUsernamePasswordAuthenticationFilter.setAuthenticationManager(authenticationManagerBean());
  466. customUsernamePasswordAuthenticationFilter.setLoadingCacheService(loadingCacheService);
  467. customUsernamePasswordAuthenticationFilter.setInvalid(invalid);
  468. customUsernamePasswordAuthenticationFilter.setSessionRegistryImpl(sessionRegistryImpl);
  469. customUsernamePasswordAuthenticationFilter.setInvaliddays(invaliddays);
  470. customUsernamePasswordAuthenticationFilter.setConcurrencyControl(concurrencyControl);
  471. customUsernamePasswordAuthenticationFilter.setConcurrencyLimit(concurrencyLimit);
  472. customUsernamePasswordAuthenticationFilter.setConcurrencyPriority(concurrencyPriority);
  473. customUsernamePasswordAuthenticationFilter.setConcurrencyHourStart(concurrencyHourStart);
  474. customUsernamePasswordAuthenticationFilter.setConcurrencyHourEnd(concurrencyHourEnd);
  475. customUsernamePasswordAuthenticationFilter
  476. .setSessionAuthenticationStrategy(concurrentSessionControlStrategy);
  477. customUsernamePasswordAuthenticationFilter.setUserService(userService);
  478. customUsernamePasswordAuthenticationFilter.setFilterProcessesUrl("/login");
  479. customUsernamePasswordAuthenticationFilter.setAllowEmptyValidateCode(true);
  480. return customUsernamePasswordAuthenticationFilter;
  481. }
  482. @Bean
  483. public MyFailureHandler customFailureHandler() {
  484. MyFailureHandler customFailureHandler = new MyFailureHandler();
  485. customFailureHandler.setDefaultFailureUrl("/zcgllogin");
  486. return customFailureHandler;
  487. }
  488. @Bean
  489. public MySuccessHandler customSuccessHandler() {
  490. MySuccessHandler customSuccessHandler = new MySuccessHandler();
  491. customSuccessHandler.setDefaultTargetUrl("/dbdc/sysframe");
  492. return customSuccessHandler;
  493. }
  494. @Bean
  495. @Override
  496. public AuthenticationManager authenticationManagerBean() throws Exception {
  497. List<AuthenticationProvider> authenticationProviderList = new ArrayList<AuthenticationProvider>();
  498. authenticationProviderList.add(customAuthenticationProvider());
  499. AuthenticationManager authenticationManager = new ProviderManager(authenticationProviderList);
  500. return authenticationManager;
  501. }
  502. @Autowired
  503. public MyUserDetailServiceImpl userDetailsService;
  504. @Bean
  505. private MyAuthenticationProvider customAuthenticationProvider() {
  506. MyAuthenticationProvider customAuthenticationProvider = new MyAuthenticationProvider();
  507. customAuthenticationProvider.setUserDetailsService(userDetailsService);
  508. return customAuthenticationProvider;
  509. }
  510. @Autowired
  511. private MenuService menuService;
  512. @Autowired
  513. private RoleService roleService;
  514. @Autowired
  515. private SessionRegistry sessionRegistry;
  516. @Bean
  517. private MySecurityMetadataSource fisMetadataSource() {
  518. MySecurityMetadataSource fisMetadataSource = new MySecurityMetadataSource();
  519. fisMetadataSource.setMenuService(menuService);
  520. fisMetadataSource.setRoleService(roleService);
  521. return fisMetadataSource;
  522. }
  523. @Autowired
  524. private cn.com.taiji.security.MyAccessDecisionManager accessDecisionManager;
  525. @Bean
  526. public MyFilterSecurityInterceptor taijifiltersecurityinterceptor() throws Exception {
  527. MyFilterSecurityInterceptor taijifiltersecurityinterceptor = new MyFilterSecurityInterceptor();
  528. taijifiltersecurityinterceptor.setFisMetadataSource(fisMetadataSource());
  529. taijifiltersecurityinterceptor.setAccessDecisionManager(accessDecisionManager);
  530. taijifiltersecurityinterceptor.setAuthenticationManager(authenticationManagerBean());
  531. return taijifiltersecurityinterceptor;
  532. }
  533. @Override
  534. protected void configure(HttpSecurity http) throws Exception {
  535. // @formatter:off
  536. http
  537. .sessionManagement()
  538. .sessionAuthenticationStrategy(concurrentSessionControlStrategy)
  539. .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
  540. .sessionFixation().changeSessionId()
  541. .maximumSessions(1)
  542. .maxSessionsPreventsLogin(true)
  543. .expiredUrl("/dbdc/sysquit")
  544. .sessionRegistry(sessionRegistry);
  545. http.authorizeRequests()
  546. .filterSecurityInterceptorOncePerRequest(true)// 过滤器的安全拦截器的每一次的要求
  547. .antMatchers("/image").permitAll() // for login
  548. .antMatchers("/dbdc/caslogin").permitAll().antMatchers("/dbdc/tjcaslogin").permitAll()
  549. .antMatchers("/dbdc/tjcaslogin").permitAll()
  550. .antMatchers("/dbdc/synchronizeInfo").permitAll().antMatchers("/monitor/isalive").permitAll()
  551. .antMatchers("/zcgllogin").permitAll().antMatchers("/dbdc_theme/**").permitAll()
  552. .antMatchers("/layuiadmin/**").permitAll().antMatchers("/layer/**").permitAll()
  553. .antMatchers("/api/**").permitAll().antMatchers("/echarts/**").permitAll()
  554. .antMatchers("/ueditor/**").permitAll().antMatchers("/uploadfile/**").permitAll()
  555. .antMatchers("/websocket-logger-js/**").permitAll().antMatchers("/soap/*").permitAll().anyRequest()
  556. .fullyAuthenticated()// .accessDecisionManager(accessDecisionManager) // all others need login
  557. .and().formLogin().loginPage("/zcgllogin").failureUrl("/zcgllogin?error")
  558. // login config
  559. .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
  560. .and().exceptionHandling().accessDeniedPage("/logout"); // exception
  561. http.csrf().disable().addFilterAfter(new PermissionFilter(), ChannelProcessingFilter.class)
  562. .addFilterAfter(new XssFilter(), ChannelProcessingFilter.class)
  563. // 增加PermissionFilter
  564. .addFilterAfter(new RefererFilter(), ChannelProcessingFilter.class).addFilter(loginFilter())
  565. .rememberMe();
  566. http.headers().frameOptions().disable();
  567. // @formatter:on
  568. }
  569. @Override
  570. public void configure(AuthenticationManagerBuilder authManagerBuilder) throws Exception {
  571. authManagerBuilder.userDetailsService(userDetailsService);
  572. }
  573. }
  574. }