WebSecurityConfig.java 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package com.genersoft.iot.vmp.conf.security;
  2. import com.genersoft.iot.vmp.conf.UserSetting;
  3. import org.junit.jupiter.api.Order;
  4. import org.slf4j.Logger;
  5. import org.slf4j.LoggerFactory;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  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. /**
  27. * 配置Spring Security
  28. * @author lin
  29. */
  30. @Configuration
  31. @EnableWebSecurity
  32. @EnableGlobalMethodSecurity(prePostEnabled = true)
  33. @Order(1)
  34. public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  35. private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);
  36. @Autowired
  37. private UserSetting userSetting;
  38. @Autowired
  39. private DefaultUserDetailsServiceImpl userDetailsService;
  40. /**
  41. * 登出成功的处理
  42. */
  43. @Autowired
  44. private LoginFailureHandler loginFailureHandler;
  45. /**
  46. * 登录成功的处理
  47. */
  48. @Autowired
  49. private LoginSuccessHandler loginSuccessHandler;
  50. /**
  51. * 登出成功的处理
  52. */
  53. @Autowired
  54. private LogoutHandler logoutHandler;
  55. /**
  56. * 未登录的处理
  57. */
  58. @Autowired
  59. private AnonymousAuthenticationEntryPoint anonymousAuthenticationEntryPoint;
  60. @Autowired
  61. private JwtAuthenticationFilter jwtAuthenticationFilter;
  62. /**
  63. * 描述: 静态资源放行,这里的放行,是不走 Spring Security 过滤器链
  64. **/
  65. @Override
  66. public void configure(WebSecurity web) {
  67. if (!userSetting.isInterfaceAuthentication()) {
  68. web.ignoring().antMatchers("**");
  69. }else {
  70. ArrayList<String> matchers = new ArrayList<>();
  71. matchers.add("/");
  72. matchers.add("/#/**");
  73. matchers.add("/static/**");
  74. matchers.add("/index.html");
  75. matchers.add("/doc.html");
  76. matchers.add("/webjars/**");
  77. matchers.add("/swagger-resources/**");
  78. matchers.add("/v3/api-docs/**");
  79. matchers.add("/js/**");
  80. matchers.add("/api/device/query/snap/**");
  81. matchers.addAll(userSetting.getInterfaceAuthenticationExcludes());
  82. // 可以直接访问的静态数据
  83. web.ignoring().antMatchers(matchers.toArray(new String[0]));
  84. }
  85. }
  86. /**
  87. * 配置认证方式
  88. * @param auth
  89. * @throws Exception
  90. */
  91. @Override
  92. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  93. DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
  94. // 设置不隐藏 未找到用户异常
  95. provider.setHideUserNotFoundExceptions(true);
  96. // 用户认证service - 查询数据库的逻辑
  97. provider.setUserDetailsService(userDetailsService);
  98. // 设置密码加密算法
  99. provider.setPasswordEncoder(passwordEncoder());
  100. auth.authenticationProvider(provider);
  101. }
  102. @Override
  103. protected void configure(HttpSecurity http) throws Exception {
  104. http.headers().contentTypeOptions().disable()
  105. .and().cors().configurationSource(configurationSource())
  106. .and().csrf().disable()
  107. .sessionManagement()
  108. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  109. // 配置拦截规则
  110. .and()
  111. .authorizeRequests()
  112. .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
  113. .antMatchers(userSetting.getInterfaceAuthenticationExcludes().toArray(new String[0])).permitAll()
  114. .antMatchers("/api/user/login","/index/hook/**").permitAll()
  115. .anyRequest().authenticated()
  116. // 异常处理器
  117. .and()
  118. .exceptionHandling()
  119. .authenticationEntryPoint(anonymousAuthenticationEntryPoint)
  120. .and().logout().logoutUrl("/api/user/logout").permitAll()
  121. .logoutSuccessHandler(logoutHandler)
  122. ;
  123. http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  124. }
  125. CorsConfigurationSource configurationSource(){
  126. // 配置跨域
  127. CorsConfiguration corsConfiguration = new CorsConfiguration();
  128. corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
  129. corsConfiguration.setAllowedMethods(Arrays.asList("*"));
  130. corsConfiguration.setMaxAge(3600L);
  131. corsConfiguration.setAllowCredentials(true);
  132. corsConfiguration.setAllowedOrigins(userSetting.getAllowedOrigins());
  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. }