WebSecurityConfig.java 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package com.genersoft.iot.vmp.conf.security;
  2. import com.genersoft.iot.vmp.conf.UserSetting;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.core.annotation.Order;
  9. import org.springframework.security.authentication.AuthenticationManager;
  10. import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
  11. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  12. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  13. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  14. import org.springframework.security.config.annotation.web.builders.WebSecurity;
  15. import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
  16. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  17. import org.springframework.security.config.http.SessionCreationPolicy;
  18. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  19. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  20. import org.springframework.web.cors.CorsConfiguration;
  21. import org.springframework.web.cors.CorsConfigurationSource;
  22. import org.springframework.web.cors.CorsUtils;
  23. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.Collections;
  27. /**
  28. * 配置Spring Security
  29. *
  30. * @author lin
  31. */
  32. @Configuration
  33. @EnableWebSecurity
  34. @EnableGlobalMethodSecurity(prePostEnabled = true)
  35. @Order(1)
  36. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  37. private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
  38. @Autowired
  39. private UserSetting userSetting;
  40. @Autowired
  41. private DefaultUserDetailsServiceImpl userDetailsService;
  42. /**
  43. * 登出成功的处理
  44. */
  45. @Autowired
  46. private LogoutHandler logoutHandler;
  47. /**
  48. * 未登录的处理
  49. */
  50. @Autowired
  51. private AnonymousAuthenticationEntryPoint anonymousAuthenticationEntryPoint;
  52. @Autowired
  53. private JwtAuthenticationFilter jwtAuthenticationFilter;
  54. /**
  55. * 描述: 静态资源放行,这里的放行,是不走 Spring Security 过滤器链
  56. **/
  57. @Override
  58. public void configure(WebSecurity web) {
  59. if (userSetting.isInterfaceAuthentication()) {
  60. ArrayList<String> matchers = new ArrayList<>();
  61. matchers.add("/");
  62. matchers.add("/#/**");
  63. matchers.add("/static/**");
  64. matchers.add("/swagger-ui.html");
  65. matchers.add("/swagger-ui/");
  66. matchers.add("/index.html");
  67. matchers.add("/doc.html");
  68. matchers.add("/webjars/**");
  69. matchers.add("/swagger-resources/**");
  70. matchers.add("/v3/api-docs/**");
  71. matchers.add("/js/**");
  72. matchers.add("/api/device/query/snap/**");
  73. matchers.add("/record_proxy/*/**");
  74. matchers.add("/api/emit");
  75. matchers.add("/favicon.ico");
  76. // 可以直接访问的静态数据
  77. web.ignoring().antMatchers(matchers.toArray(new String[0]));
  78. }
  79. }
  80. /**
  81. * 配置认证方式
  82. *
  83. * @param auth
  84. * @throws Exception
  85. */
  86. @Override
  87. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  88. DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
  89. // 设置不隐藏 未找到用户异常
  90. provider.setHideUserNotFoundExceptions(true);
  91. // 用户认证service - 查询数据库的逻辑
  92. provider.setUserDetailsService(userDetailsService);
  93. // 设置密码加密算法
  94. provider.setPasswordEncoder(passwordEncoder());
  95. auth.authenticationProvider(provider);
  96. }
  97. @Override
  98. protected void configure(HttpSecurity http) throws Exception {
  99. http.headers().contentTypeOptions().disable()
  100. .and().cors().configurationSource(configurationSource())
  101. .and().csrf().disable()
  102. .sessionManagement()
  103. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  104. // 配置拦截规则
  105. .and()
  106. .authorizeRequests()
  107. .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
  108. .antMatchers(userSetting.getInterfaceAuthenticationExcludes().toArray(new String[0])).permitAll()
  109. .antMatchers("/api/user/login", "/index/hook/**", "/swagger-ui/**", "/doc.html").permitAll()
  110. .anyRequest().authenticated()
  111. // 异常处理器
  112. .and()
  113. .exceptionHandling()
  114. .authenticationEntryPoint(anonymousAuthenticationEntryPoint)
  115. .and().logout().logoutUrl("/api/user/logout").permitAll()
  116. .logoutSuccessHandler(logoutHandler)
  117. ;
  118. http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  119. }
  120. CorsConfigurationSource configurationSource() {
  121. // 配置跨域
  122. CorsConfiguration corsConfiguration = new CorsConfiguration();
  123. corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
  124. corsConfiguration.setAllowedMethods(Arrays.asList("*"));
  125. corsConfiguration.setMaxAge(3600L);
  126. if (userSetting.getAllowedOrigins() != null && !userSetting.getAllowedOrigins().isEmpty()) {
  127. corsConfiguration.setAllowCredentials(true);
  128. corsConfiguration.setAllowedOrigins(userSetting.getAllowedOrigins());
  129. }else {
  130. corsConfiguration.setAllowCredentials(false);
  131. corsConfiguration.setAllowedOrigins(Collections.singletonList(CorsConfiguration.ALL));
  132. }
  133. corsConfiguration.setExposedHeaders(Arrays.asList(JwtUtils.getHeader()));
  134. UrlBasedCorsConfigurationSource url = new UrlBasedCorsConfigurationSource();
  135. url.registerCorsConfiguration("/**", corsConfiguration);
  136. return url;
  137. }
  138. /**
  139. * 描述: 密码加密算法 BCrypt 推荐使用
  140. **/
  141. @Bean
  142. public BCryptPasswordEncoder passwordEncoder() {
  143. return new BCryptPasswordEncoder();
  144. }
  145. /**
  146. * 描述: 注入AuthenticationManager管理器
  147. **/
  148. @Override
  149. @Bean
  150. public AuthenticationManager authenticationManager() throws Exception {
  151. return super.authenticationManager();
  152. }
  153. }