Browse Source

Merge remote-tracking branch 'origin/main'

Sakana 5 days ago
parent
commit
bd384b93c4
16 changed files with 561 additions and 0 deletions
  1. 5 0
      edu-travel-common/edu-travel-common-core/pom.xml
  2. 31 0
      edu-travel-service/edu-travel-service-tomcat/pom.xml
  3. 17 0
      edu-travel-service/edu-travel-service-tomcat/src/main/java/edu/travel/App.java
  4. 135 0
      edu-travel-service/edu-travel-service-ws/pom.xml
  5. 17 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/WsApplication.java
  6. 32 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/MyAccessDeniedHandler.java
  7. 31 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/MyAuthenticationEntryPoint.java
  8. 39 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/ResourceServerConfig.java
  9. 48 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/TokenConfig.java
  10. 21 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebSecurityConfig.java
  11. 23 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebServerFactoryConfigs.java
  12. 25 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebSocketAutoConfig.java
  13. 61 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/filter/TokenAuthenticationFilter.java
  14. 12 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/handle/TravelMessageHandler.java
  15. 62 0
      edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/interceptor/SystemMessageInterceptor.java
  16. 2 0
      edu-travel-service/pom.xml

+ 5 - 0
edu-travel-common/edu-travel-common-core/pom.xml

@@ -19,6 +19,11 @@
 
     <dependencies>
         <dependency>
+            <groupId>org.codehaus.groovy</groupId>
+            <artifactId>groovy</artifactId>
+        </dependency>
+
+        <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
             <scope>provided</scope>

+ 31 - 0
edu-travel-service/edu-travel-service-tomcat/pom.xml

@@ -0,0 +1,31 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>edu.travel</groupId>
+        <artifactId>edu-travel-service</artifactId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>edu-travel-service-tomcat</artifactId>
+    <packaging>jar</packaging>
+
+    <name>edu-travel-service-tomcat</name>
+    <url>http://maven.apache.org</url>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-common-core</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+    </dependencies>
+</project>

+ 17 - 0
edu-travel-service/edu-travel-service-tomcat/src/main/java/edu/travel/App.java

@@ -0,0 +1,17 @@
+package edu.travel;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ * Hello world!
+ *
+ */
+@SpringBootApplication
+public class App 
+{
+    public static void main( String[] args )
+    {
+       SpringApplication.run(App.class, args);
+    }
+}

+ 135 - 0
edu-travel-service/edu-travel-service-ws/pom.xml

@@ -0,0 +1,135 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>edu.travel</groupId>
+        <artifactId>edu-travel-service</artifactId>
+        <version>1.0-SNAPSHOT</version>
+    </parent>
+
+    <artifactId>edu-travel-service-ws</artifactId>
+    <packaging>jar</packaging>
+
+    <name>edu-travel-service-ws</name>
+    <url>http://maven.apache.org</url>
+
+    <properties>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-websocket</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-validation</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-zipkin</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-security</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-oauth2</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>mysql</groupId>
+            <artifactId>mysql-connector-java</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-bootstrap</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>javax.servlet-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>cn.hutool</groupId>
+            <artifactId>hutool-all</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba</groupId>
+            <artifactId>fastjson</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-transport-simple-http</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-annotation-aspectj</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.cloud</groupId>
+            <artifactId>spring-cloud-alibaba-sentinel-datasource</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-datasource-nacos</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>com.alibaba.csp</groupId>
+            <artifactId>sentinel-web-servlet</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-common-util</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-model-base</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-common-cache</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-common-datasource</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+        <dependency>
+            <groupId>edu.travel</groupId>
+            <artifactId>edu-travel-common-constant</artifactId>
+            <version>1.0-SNAPSHOT</version>
+        </dependency>
+
+
+
+
+    </dependencies>
+</project>

+ 17 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/WsApplication.java

@@ -0,0 +1,17 @@
+package edu.travel;
+
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
+
+
+@SpringBootApplication
+@EnableDiscoveryClient
+@MapperScan
+public class WsApplication
+{
+    public static void main( String[] args )
+    {
+        System.out.println( "Hello World!" );
+    }
+}

+ 32 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/MyAccessDeniedHandler.java

@@ -0,0 +1,32 @@
+package edu.travel.ws.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.security.access.AccessDeniedException;
+import org.springframework.security.web.access.AccessDeniedHandler;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class MyAccessDeniedHandler  implements AccessDeniedHandler {
+    @Override
+    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {
+        resp.setContentType("application/json;charset=UTF-8");
+        Map map = new HashMap();
+        map.put("code", "450");
+        map.put("message", e.getMessage());
+        map.put("path", req.getServletPath());
+        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
+        resp.setContentType("application/json");
+        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.writeValue(resp.getOutputStream(), map);
+        } catch (Exception ex) {
+            throw new ServletException();
+        }
+    }
+}

+ 31 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/MyAuthenticationEntryPoint.java

@@ -0,0 +1,31 @@
+package edu.travel.ws.config;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
+    @Override
+    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
+        Map map = new HashMap();
+        map.put("code", "451");
+        map.put("message", "无权限访问");
+        map.put("path", httpServletRequest.getServletPath());
+        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
+        httpServletResponse.setContentType("application/json");
+        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.writeValue(httpServletResponse.getOutputStream(), map);
+        } catch (Exception ex) {
+            throw new ServletException();
+        }
+    }
+}

+ 39 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/ResourceServerConfig.java

@@ -0,0 +1,39 @@
+package edu.travel.ws.config;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
+import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+
+@Configuration
+@EnableResourceServer
+public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
+    private static  final String RESOURCE_ID = "admin";
+
+    @Autowired
+    private TokenStore tokenStore;
+
+    @Override
+    public void configure(ResourceServerSecurityConfigurer resources) {
+        resources.resourceId(RESOURCE_ID)//资源 id
+                .tokenStore(tokenStore)
+                .authenticationEntryPoint(new MyAuthenticationEntryPoint())
+                .accessDeniedHandler(new MyAccessDeniedHandler())
+//                .tokenServices(tokenService())//验证令牌的服务
+                .stateless(true);
+    }
+
+    @Override
+    public void configure(HttpSecurity http) throws Exception {
+
+        http
+                .authorizeRequests()
+                .antMatchers("/**").permitAll()
+                .and().csrf().disable()
+                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
+    }
+}

+ 48 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/TokenConfig.java

@@ -0,0 +1,48 @@
+package edu.travel.ws.config;
+
+import edu.travel.RSAUtill;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.crypto.password.NoOpPasswordEncoder;
+import org.springframework.security.crypto.password.PasswordEncoder;
+import org.springframework.security.oauth2.provider.token.TokenStore;
+import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
+import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
+
+import java.security.PrivateKey;
+
+@Configuration
+public class TokenConfig {
+    @Value("${OAUTH_KEY}")
+    private String key;
+    @Value("${PRIVATE_KEY}")
+    private String privateKey;
+    @Bean
+    public PasswordEncoder passwordEncoder(){
+        return NoOpPasswordEncoder.getInstance();
+    }
+    @Bean
+    public TokenStore tokenStore() {
+        //JWT令牌存储方案
+        return new JwtTokenStore(accessTokenConverter());
+    }
+
+    @Bean
+    public JwtAccessTokenConverter accessTokenConverter() {
+        try {
+            PrivateKey privateKeyFromString = RSAUtill.getPrivateKeyFromString(privateKey);
+            String decrypt = RSAUtill.decrypt(key, privateKeyFromString);
+            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
+            //对称秘钥,资源服务器使用该秘钥来验证
+//        converter.setKeyPair(keyPair());
+            converter.setSigningKey(decrypt);
+            return converter;
+
+        }catch (Exception e){
+            e.printStackTrace();
+            return null;
+        }
+
+    }
+}

+ 21 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebSecurityConfig.java

@@ -0,0 +1,21 @@
+package edu.travel.ws.config;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
+import org.springframework.security.config.annotation.web.builders.HttpSecurity;
+import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
+
+@Configuration
+@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
+public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
+    //安全拦截机制(最重要)
+    @Override
+    protected void configure(HttpSecurity http) throws Exception {
+        http.csrf().disable()
+                .authorizeRequests()
+                .anyRequest().authenticated()
+        ;
+
+
+    }
+}

+ 23 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebServerFactoryConfigs.java

@@ -0,0 +1,23 @@
+package edu.travel.ws.config;
+
+import org.apache.catalina.connector.Connector;
+import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
+import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
+import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+@Configuration
+public class WebServerFactoryConfigs {
+    @Bean
+    public ConfigurableServletWebServerFactory webServerFactory() {
+        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
+        factory.addConnectorCustomizers(new TomcatConnectorCustomizer() {
+            @Override
+            public void customize(Connector connector) {
+                connector.setProperty("relaxedQueryChars", "|{}[]");
+            }
+        });
+        return factory;
+    }
+}

+ 25 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/config/WebSocketAutoConfig.java

@@ -0,0 +1,25 @@
+package edu.travel.ws.config;
+
+import edu.travel.ws.handle.TravelMessageHandler;
+import edu.travel.ws.interceptor.SystemMessageInterceptor;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.web.socket.config.annotation.EnableWebSocket;
+import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
+import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
+
+@Configuration
+@EnableWebSocket
+public class WebSocketAutoConfig implements WebSocketConfigurer {
+
+    @Autowired
+    private ApplicationContext applicationContext;
+
+    @Override
+    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
+        registry.addHandler(new TravelMessageHandler(applicationContext), "/system/message")
+                .addInterceptors(new SystemMessageInterceptor(applicationContext))
+                .setAllowedOrigins("*");
+    }
+}

+ 61 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/filter/TokenAuthenticationFilter.java

@@ -0,0 +1,61 @@
+package edu.travel.ws.filter;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import edu.travel.EncryptUtil;
+import edu.travel.entity.EduTenantPO;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.authority.AuthorityUtils;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+@Component
+public class TokenAuthenticationFilter extends OncePerRequestFilter {
+    @Autowired
+    private RedisTemplate redisTemplate;
+    @Override
+    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
+        String token = httpServletRequest.getHeader("token");
+//token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsiYWRtaW4iXSwiZXhwIjoxNzQwMjAyNTcyLCJ1c2VyX25hbWUiOiIxNTk5ODk1NzA3NCIsImp0aSI6IjM0M2JjNGUzLTk5ZjMtNGE4Zi1iMmIxLTI1ZjRkMzBmNmJmYyIsImNsaWVudF9pZCI6ImFkbWluIiwic2NvcGUiOlsic2VydmVyIl19.MYoFq8gg832DQMX-wVMLN0JlIaWeuQZvl1z1NUNFspQ";
+        if (StringUtils.isNotBlank(token)){
+            String json = EncryptUtil.decodeUTF8StringBase64(token);
+            //将token转成json对象
+            JSONObject jsonObject = JSON.parseObject(json);
+            //用户身份信息
+            String username  = jsonObject.getString("principal");
+            Object object = redisTemplate.opsForValue().get(username + "_info");
+            if (object == null){
+                JSONObject resultObject = new JSONObject();
+                resultObject.put("code",401);
+                resultObject.put("msg","not found user");
+                resultObject.put("data",null);
+                httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+                httpServletResponse.setContentType("application/json;charset=utf-8");
+                httpServletResponse.getWriter().write(resultObject.toJSONString());
+                return;
+            }
+            EduTenantPO eduTenant = JSON.parseObject(object.toString(), EduTenantPO.class);
+            //用户权限
+            JSONArray authoritiesArray = jsonObject.getJSONArray("authorities");
+            String[] authorities = authoritiesArray.toArray(new String[authoritiesArray.size()]);
+            //将用户信息和权限填充 到用户身份token对象中
+            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(eduTenant, null, AuthorityUtils.createAuthorityList(authorities));
+            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
+            //将authenticationToken填充到安全上下文
+            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+        }
+        filterChain.doFilter(httpServletRequest,httpServletResponse);
+    }
+}

+ 12 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/handle/TravelMessageHandler.java

@@ -0,0 +1,12 @@
+package edu.travel.ws.handle;
+
+import org.springframework.context.ApplicationContext;
+import org.springframework.web.socket.handler.AbstractWebSocketHandler;
+
+public class TravelMessageHandler extends AbstractWebSocketHandler {
+    private ApplicationContext applicationContext;
+
+    public TravelMessageHandler(ApplicationContext applicationContext) {
+        this.applicationContext = applicationContext;
+    }
+}

+ 62 - 0
edu-travel-service/edu-travel-service-ws/src/main/java/edu/travel/ws/interceptor/SystemMessageInterceptor.java

@@ -0,0 +1,62 @@
+package edu.travel.ws.interceptor;
+
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import edu.travel.EncryptUtil;
+import edu.travel.entity.EduTenantPO;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.context.ApplicationContext;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.http.server.ServerHttpRequest;
+import org.springframework.http.server.ServerHttpResponse;
+import org.springframework.http.server.ServletServerHttpRequest;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.authority.AuthorityUtils;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.web.socket.WebSocketHandler;
+import org.springframework.web.socket.server.HandshakeInterceptor;
+
+import java.util.Map;
+
+public class SystemMessageInterceptor implements HandshakeInterceptor {
+    private ApplicationContext applicationContext;
+    public SystemMessageInterceptor(ApplicationContext applicationContext) {
+        this.applicationContext = applicationContext;
+    }
+    @Override
+    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
+        RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
+        if (request instanceof ServletServerHttpRequest){
+            ServletServerHttpRequest httpRequest = (ServletServerHttpRequest) request;
+            String token = httpRequest.getServletRequest().getParameter("token");
+            if (StringUtils.isBlank(token)){
+                return false;
+            }
+            String json = EncryptUtil.decodeUTF8StringBase64(token);
+            //将token转成json对象
+            JSONObject jsonObject = JSON.parseObject(json);
+            //用户身份信息
+            String username  = jsonObject.getString("principal");
+            Object object = redisTemplate.opsForValue().get(username + "_info");
+            EduTenantPO eduTenant = JSON.parseObject(object.toString(), EduTenantPO.class);
+            //用户权限
+            JSONArray authoritiesArray = jsonObject.getJSONArray("authorities");
+            String[] authorities = authoritiesArray.toArray(new String[authoritiesArray.size()]);
+            //将用户信息和权限填充 到用户身份token对象中
+            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(eduTenant, null, AuthorityUtils.createAuthorityList(authorities));
+            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest.getServletRequest()));
+            //将authenticationToken填充到安全上下文
+            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
+            attributes.put("user", eduTenant);
+            return true;
+        }
+        return false;
+    }
+
+    @Override
+    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
+
+    }
+}

+ 2 - 0
edu-travel-service/pom.xml

@@ -19,6 +19,8 @@
         <module>edu-travel-service-upload</module>
         <module>edu-travel-service-debezium</module>
         <module>edu-travel-service-education</module>
+        <module>edu-travel-service-tomcat</module>
+        <module>edu-travel-service-ws</module>
     </modules>
 
     <name>edu-travel-service</name>