WebSecurityConfig.java 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. package com.genersoft.iot.vmp.conf.security;
  2. import com.genersoft.iot.vmp.conf.UserSetting;
  3. import org.springframework.core.annotation.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 LogoutHandler logoutHandler;
  45. /**
  46. * 未登录的处理
  47. */
  48. @Autowired
  49. private AnonymousAuthenticationEntryPoint anonymousAuthenticationEntryPoint;
  50. @Autowired
  51. private JwtAuthenticationFilter jwtAuthenticationFilter;
  52. /**
  53. * 描述: 静态资源放行,这里的放行,是不走 Spring Security 过滤器链
  54. **/
  55. @Override
  56. public void configure(WebSecurity web) {
  57. if (userSetting.isInterfaceAuthentication()) {
  58. ArrayList<String> matchers = new ArrayList<>();
  59. matchers.add("/");
  60. matchers.add("/#/**");
  61. matchers.add("/static/**");
  62. matchers.add("/index.html");
  63. matchers.add("/doc.html");
  64. matchers.add("/webjars/**");
  65. matchers.add("/swagger-resources/**");
  66. matchers.add("/v3/api-docs/**");
  67. matchers.add("/js/**");
  68. matchers.add("/api/device/query/snap/**");
  69. matchers.add("/record_proxy/*/**");
  70. // 可以直接访问的静态数据
  71. web.ignoring().antMatchers(matchers.toArray(new String[0]));
  72. }
  73. }
  74. /**
  75. * 配置认证方式
  76. * @param auth
  77. * @throws Exception
  78. */
  79. @Override
  80. protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  81. DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
  82. // 设置不隐藏 未找到用户异常
  83. provider.setHideUserNotFoundExceptions(true);
  84. // 用户认证service - 查询数据库的逻辑
  85. provider.setUserDetailsService(userDetailsService);
  86. // 设置密码加密算法
  87. provider.setPasswordEncoder(passwordEncoder());
  88. auth.authenticationProvider(provider);
  89. }
  90. @Override
  91. protected void configure(HttpSecurity http) throws Exception {
  92. http.headers().contentTypeOptions().disable()
  93. .and().cors().configurationSource(configurationSource())
  94. .and().csrf().disable()
  95. .sessionManagement()
  96. .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  97. // 配置拦截规则
  98. .and()
  99. .authorizeRequests()
  100. .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
  101. .antMatchers(userSetting.getInterfaceAuthenticationExcludes().toArray(new String[0])).permitAll()
  102. .antMatchers("/api/user/login","/index/hook/**","/zlm_Proxy/FhTuMYqB2HeCuNOb/record/t/1/2023-03-25/16:35:07-16:35:16-9353.mp4").permitAll()
  103. .anyRequest().authenticated()
  104. // 异常处理器
  105. .and()
  106. .exceptionHandling()
  107. .authenticationEntryPoint(anonymousAuthenticationEntryPoint)
  108. .and().logout().logoutUrl("/api/user/logout").permitAll()
  109. .logoutSuccessHandler(logoutHandler)
  110. ;
  111. http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
  112. }
  113. CorsConfigurationSource configurationSource(){
  114. // 配置跨域
  115. CorsConfiguration corsConfiguration = new CorsConfiguration();
  116. corsConfiguration.setAllowedHeaders(Arrays.asList("*"));
  117. corsConfiguration.setAllowedMethods(Arrays.asList("*"));
  118. corsConfiguration.setMaxAge(3600L);
  119. corsConfiguration.setAllowCredentials(true);
  120. corsConfiguration.setAllowedOrigins(userSetting.getAllowedOrigins());
  121. corsConfiguration.setExposedHeaders(Arrays.asList(JwtUtils.getHeader()));
  122. UrlBasedCorsConfigurationSource url = new UrlBasedCorsConfigurationSource();
  123. url.registerCorsConfiguration("/**",corsConfiguration);
  124. return url;
  125. }
  126. /**
  127. * 描述: 密码加密算法 BCrypt 推荐使用
  128. **/
  129. @Bean
  130. public BCryptPasswordEncoder passwordEncoder() {
  131. return new BCryptPasswordEncoder();
  132. }
  133. /**
  134. * 描述: 注入AuthenticationManager管理器
  135. **/
  136. @Override
  137. @Bean
  138. public AuthenticationManager authenticationManager() throws Exception {
  139. return super.authenticationManager();
  140. }
  141. }