SecurityConfig.java 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package com.hydropower.framework.config;
  2. import com.google.common.collect.Lists;
  3. import lombok.extern.slf4j.Slf4j;
  4. import lombok.val;
  5. import org.checkerframework.checker.nullness.qual.Nullable;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.http.HttpMethod;
  9. import org.springframework.security.authentication.AuthenticationManager;
  10. import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
  11. import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
  12. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  13. import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
  14. import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
  15. import org.springframework.security.config.http.SessionCreationPolicy;
  16. import org.springframework.security.core.userdetails.UserDetailsService;
  17. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  18. import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
  19. import org.springframework.security.web.authentication.logout.LogoutFilter;
  20. import org.springframework.security.web.header.Header;
  21. import org.springframework.security.web.header.writers.CrossOriginOpenerPolicyHeaderWriter;
  22. import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
  23. import org.springframework.security.web.header.writers.StaticHeadersWriter;
  24. import org.springframework.web.cors.CorsConfiguration;
  25. import org.springframework.web.cors.CorsConfigurationSource;
  26. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  27. import org.springframework.web.filter.CorsFilter;
  28. import com.hydropower.framework.config.properties.PermitAllUrlProperties;
  29. import com.hydropower.framework.security.filter.JwtAuthenticationTokenFilter;
  30. import com.hydropower.framework.security.handle.AuthenticationEntryPointImpl;
  31. import com.hydropower.framework.security.handle.LogoutSuccessHandlerImpl;
  32. import java.util.ArrayList;
  33. import java.util.Arrays;
  34. import java.util.List;
  35. /**
  36. * spring security配置
  37. *
  38. * @author ruoyi
  39. */
  40. @Slf4j
  41. @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
  42. public class SecurityConfig extends WebSecurityConfigurerAdapter
  43. {
  44. /**
  45. * 自定义用户认证逻辑
  46. */
  47. @Autowired
  48. private UserDetailsService userDetailsService;
  49. /**
  50. * 认证失败处理类
  51. */
  52. @Autowired
  53. private AuthenticationEntryPointImpl unauthorizedHandler;
  54. /**
  55. * 退出处理类
  56. */
  57. @Autowired
  58. private LogoutSuccessHandlerImpl logoutSuccessHandler;
  59. /**
  60. * token认证过滤器
  61. */
  62. @Autowired
  63. private JwtAuthenticationTokenFilter authenticationTokenFilter;
  64. /**
  65. * 允许匿名访问的地址
  66. */
  67. @Autowired
  68. private PermitAllUrlProperties permitAllUrl;
  69. /**
  70. * 解决 无法直接注入 AuthenticationManager
  71. *
  72. * @return
  73. * @throws Exception
  74. */
  75. @Bean
  76. @Override
  77. public AuthenticationManager authenticationManagerBean() throws Exception
  78. {
  79. return super.authenticationManagerBean();
  80. }
  81. /**
  82. * anyRequest | 匹配所有请求路径
  83. * access | SpringEl表达式结果为true时可以访问
  84. * anonymous | 匿名可以访问
  85. * denyAll | 用户不能访问
  86. * fullyAuthenticated | 用户完全认证可以访问(非remember-me下自动登录)
  87. * hasAnyAuthority | 如果有参数,参数表示权限,则其中任何一个权限可以访问
  88. * hasAnyRole | 如果有参数,参数表示角色,则其中任何一个角色可以访问
  89. * hasAuthority | 如果有参数,参数表示权限,则其权限可以访问
  90. * hasIpAddress | 如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
  91. * hasRole | 如果有参数,参数表示角色,则其角色可以访问
  92. * permitAll | 用户可以任意访问
  93. * rememberMe | 允许通过remember-me登录的用户访问
  94. * authenticated | 用户登录后可访问
  95. */
  96. @Override
  97. protected void configure(HttpSecurity httpSecurity) throws Exception
  98. {
  99. // 注解标记允许匿名访问的url
  100. ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
  101. permitAllUrl.getUrls().forEach(url -> {
  102. registry.antMatchers(url).permitAll();
  103. log.info("add ignore auth url: {}", url);
  104. });
  105. httpSecurity
  106. // CSRF禁用,因为不使用session
  107. .csrf().disable()
  108. // 认证失败处理类
  109. .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
  110. // 基于token,所以不需要session
  111. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
  112. // 过滤请求
  113. .authorizeRequests()
  114. // 对于登录login 注册register 验证码captchaImage 允许匿名访问
  115. .antMatchers("/login", "/register", "/captchaImage","/websocket/**","/rabbitmq/**","/api/**").permitAll()
  116. // 静态资源,可匿名访问
  117. .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
  118. .antMatchers("/swagger-ui.html", "/favicon.ico", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**", "/static/**").permitAll()
  119. // 除上面外的所有请求全部需要鉴权认证
  120. .anyRequest().authenticated()
  121. .and()
  122. .cors().configurationSource(corsConfigurationSource())
  123. .and()
  124. // 禁用HTTP响应标头
  125. .headers().cacheControl().disable().and()
  126. .headers(headers -> {
  127. headers.referrerPolicy().policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN);
  128. headers.frameOptions().disable();
  129. final List<@Nullable Header> headerList = Lists.newArrayList();
  130. headerList.add(new Header("Access-Control-Allow-Origin", "*"));
  131. headerList.add(new Header("Access-Control-Allow-Methods", "*"));
  132. headerList.add(new Header("Access-Control-Max-Age", "3600"));
  133. headers.addHeaderWriter(new StaticHeadersWriter(headerList));
  134. });
  135. // 添加Logout filter
  136. httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
  137. // 添加JWT filter
  138. httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
  139. // 添加CORS filter
  140. //httpSecurity.addFilterBefore(authenticationTokenFilter, LogoutFilter.class);
  141. //httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
  142. }
  143. //配置跨域访问资源
  144. private CorsConfigurationSource corsConfigurationSource() {
  145. CorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
  146. CorsConfiguration corsConfiguration = new CorsConfiguration();
  147. corsConfiguration.addAllowedOriginPattern("*");
  148. corsConfiguration.addAllowedOrigin("*"); // 同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
  149. corsConfiguration.addAllowedHeader("*");// header,允许哪些header,本案中使用的是token,此处可将*替换为token;
  150. corsConfiguration.addAllowedMethod("*"); // 允许的请求方法,PSOT、GET等
  151. ((UrlBasedCorsConfigurationSource) source).registerCorsConfiguration("/**", corsConfiguration); // 配置允许跨域访问的url
  152. return source;
  153. }
  154. /**
  155. * 强散列哈希加密实现
  156. */
  157. @Bean
  158. public BCryptPasswordEncoder bCryptPasswordEncoder()
  159. {
  160. return new BCryptPasswordEncoder();
  161. }
  162. /**
  163. * 身份认证接口
  164. */
  165. @Override
  166. protected void configure(AuthenticationManagerBuilder auth) throws Exception
  167. {
  168. auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
  169. }
  170. }