中国算力平台算力登记系统2.0
yanzhaofeige
2024-09-30 3c4fee1db116c11d4f04727cfe076d7c94daeaf2
commit | author | age
43dc29 1 package com.odcc.cpzidc.framework.config;
Y 2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.context.annotation.Bean;
5 import org.springframework.context.annotation.Configuration;
6 import org.springframework.http.HttpMethod;
7 import org.springframework.security.authentication.AuthenticationManager;
8 import org.springframework.security.authentication.ProviderManager;
9 import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
10 import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
11 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
12 import org.springframework.security.config.http.SessionCreationPolicy;
13 import org.springframework.security.core.userdetails.UserDetailsService;
14 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
15 import org.springframework.security.web.SecurityFilterChain;
16 import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
17 import org.springframework.security.web.authentication.logout.LogoutFilter;
18 import org.springframework.web.filter.CorsFilter;
19 import com.odcc.cpzidc.framework.config.properties.PermitAllUrlProperties;
20 import com.odcc.cpzidc.framework.security.filter.JwtAuthenticationTokenFilter;
21 import com.odcc.cpzidc.framework.security.handle.AuthenticationEntryPointImpl;
22 import com.odcc.cpzidc.framework.security.handle.LogoutSuccessHandlerImpl;
23
24 /**
25  * spring security配置
26  * 
27  * @author ruoyi
28  */
29 @EnableMethodSecurity(prePostEnabled = true, securedEnabled = true)
30 @Configuration
31 public class SecurityConfig
32 {
33     /**
34      * 自定义用户认证逻辑
35      */
36     @Autowired
37     private UserDetailsService userDetailsService;
38     
39     /**
40      * 认证失败处理类
41      */
42     @Autowired
43     private AuthenticationEntryPointImpl unauthorizedHandler;
44
45     /**
46      * 退出处理类
47      */
48     @Autowired
49     private LogoutSuccessHandlerImpl logoutSuccessHandler;
50
51     /**
52      * token认证过滤器
53      */
54     @Autowired
55     private JwtAuthenticationTokenFilter authenticationTokenFilter;
56     
57     /**
58      * 跨域过滤器
59      */
60     @Autowired
61     private CorsFilter corsFilter;
62
63     /**
64      * 允许匿名访问的地址
65      */
66     @Autowired
67     private PermitAllUrlProperties permitAllUrl;
68
69     /**
70      * 身份验证实现
71      */
72     @Bean
73     public AuthenticationManager authenticationManager()
74     {
75         DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
76         daoAuthenticationProvider.setUserDetailsService(userDetailsService);
77         daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder());
78         return new ProviderManager(daoAuthenticationProvider);
79     }
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     @Bean
97     protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception
98     {
99         return httpSecurity
100             // CSRF禁用,因为不使用session
101             .csrf(csrf -> csrf.disable())
102             // 禁用HTTP响应标头
103             .headers((headersCustomizer) -> {
104                 headersCustomizer.cacheControl(cache -> cache.disable()).frameOptions(options -> options.sameOrigin());
105             })
106             // 认证失败处理类
107             .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
108             // 基于token,所以不需要session
109             .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
110             // 注解标记允许匿名访问的url
111             .authorizeHttpRequests((requests) -> {
112                 permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll());
113                 // 对于登录login 注册register 验证码captchaImage 允许匿名访问
114                 requests.antMatchers("/login", "/register", "/captchaImage").permitAll()
115                     // 静态资源,可匿名访问
116                     .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
117                     .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
118                     // 除上面外的所有请求全部需要鉴权认证
119                     .anyRequest().authenticated();
120             })
121             // 添加Logout filter
122             .logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler))
123             // 添加JWT filter
124             .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
125             // 添加CORS filter
126             .addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class)
127             .addFilterBefore(corsFilter, LogoutFilter.class)
128             .build();
129     }
130
131     /**
132      * 强散列哈希加密实现
133      */
134     @Bean
135     public BCryptPasswordEncoder bCryptPasswordEncoder()
136     {
137         return new BCryptPasswordEncoder();
138     }
139 }