-
admin
2024-05-17 68f0c8f92fb7c82dc447b9aaed2d23760c546f25
提交 | 用户 | 时间
e57a89 1 package com.jcdm.framework.config;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.context.annotation.Bean;
5 import org.springframework.http.HttpMethod;
6 import org.springframework.security.authentication.AuthenticationManager;
7 import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
8 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
9 import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11 import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
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.authentication.UsernamePasswordAuthenticationFilter;
16 import org.springframework.security.web.authentication.logout.LogoutFilter;
17 import org.springframework.web.filter.CorsFilter;
18 import com.jcdm.framework.config.properties.PermitAllUrlProperties;
19 import com.jcdm.framework.security.filter.JwtAuthenticationTokenFilter;
20 import com.jcdm.framework.security.handle.AuthenticationEntryPointImpl;
21 import com.jcdm.framework.security.handle.LogoutSuccessHandlerImpl;
22
23 /**
24  * spring security配置
25  * 
26  * @author jc
27  */
28 @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
29 public class SecurityConfig extends WebSecurityConfigurerAdapter
30 {
31     /**
32      * 自定义用户认证逻辑
33      */
34     @Autowired
35     private UserDetailsService userDetailsService;
36     
37     /**
38      * 认证失败处理类
39      */
40     @Autowired
41     private AuthenticationEntryPointImpl unauthorizedHandler;
42
43     /**
44      * 退出处理类
45      */
46     @Autowired
47     private LogoutSuccessHandlerImpl logoutSuccessHandler;
48
49     /**
50      * token认证过滤器
51      */
52     @Autowired
53     private JwtAuthenticationTokenFilter authenticationTokenFilter;
54     
55     /**
56      * 跨域过滤器
57      */
58     @Autowired
59     private CorsFilter corsFilter;
60
61     /**
62      * 允许匿名访问的地址
63      */
64     @Autowired
65     private PermitAllUrlProperties permitAllUrl;
66
67     /**
68      * 解决 无法直接注入 AuthenticationManager
69      *
70      * @return
71      * @throws Exception
72      */
73     @Bean
74     @Override
75     public AuthenticationManager authenticationManagerBean() throws Exception
76     {
77         return super.authenticationManagerBean();
78     }
79
80     /**
81      * anyRequest          |   匹配所有请求路径
82      * access              |   SpringEl表达式结果为true时可以访问
83      * anonymous           |   匿名可以访问
84      * denyAll             |   用户不能访问
85      * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
86      * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
87      * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
88      * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
89      * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
90      * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
91      * permitAll           |   用户可以任意访问
92      * rememberMe          |   允许通过remember-me登录的用户访问
93      * authenticated       |   用户登录后可访问
94      */
95     @Override
96     protected void configure(HttpSecurity httpSecurity) throws Exception
97     {
98         // 注解标记允许匿名访问的url
99         ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
100         permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
101
102         httpSecurity
103                 // CSRF禁用,因为不使用session
104                 .csrf().disable()
105                 // 禁用HTTP响应标头
106                 .headers().cacheControl().disable().and()
107                 // 认证失败处理类
108                 .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
109                 // 基于token,所以不需要session
110                 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
111                 // 过滤请求
112                 .authorizeRequests()
113                 // 对于登录login 注册register 验证码captchaImage 允许匿名访问
2c7661 114                 .antMatchers("/login", "/register", "/captchaImage","/websocket/**","/postWebsocket/**","/em/inspectionPlanTask/**","/em/inspectionPlanItemsProject/**").permitAll()
e57a89 115                 // 静态资源,可匿名访问
116                 .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
117                 .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
8c05d8 118                 .antMatchers("/sendDemo/push").permitAll()
68f0c8 119                 .antMatchers("/jcdmMes/**").permitAll()
5966d6 120                 .antMatchers("/da/testDeviceInterface/**").permitAll()
A 121                 .antMatchers("/main/paramCollection/**").permitAll()
e57a89 122                 // 除上面外的所有请求全部需要鉴权认证
123                 .anyRequest().authenticated()
124                 .and()
125                 .headers().frameOptions().disable();
126         // 添加Logout filter
127         httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
128         // 添加JWT filter
129         httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
130         // 添加CORS filter
131         httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
132         httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
133     }
134
135     /**
136      * 强散列哈希加密实现
137      */
138     @Bean
139     public BCryptPasswordEncoder bCryptPasswordEncoder()
140     {
141         return new BCryptPasswordEncoder();
142     }
143
144     /**
145      * 身份认证接口
146      */
147     @Override
148     protected void configure(AuthenticationManagerBuilder auth) throws Exception
149     {
150         auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
151     }
152 }