martin 3 tahun lalu
induk
melakukan
feb11d515b

+ 5 - 3
simulation-resource-common/src/main/java/com/css/simulation/resource/common/controller/MinioController.java

@@ -1,5 +1,6 @@
 package com.css.simulation.resource.common.controller;
 
+import api.common.pojo.common.ResponseBodyVO;
 import com.css.simulation.resource.common.pojo.parameter.MinioParameter;
 import com.css.simulation.resource.common.util.FileUtil;
 import com.css.simulation.resource.common.util.MinioUtil;
@@ -33,11 +34,10 @@ public class MinioController {
     }
 
     @RequestMapping("/upload")
-    public void upload(
+    public ResponseBodyVO<String> upload(
             @RequestParam("file") MultipartFile multipartFile,
             @RequestParam("bucketName") String bucketName,
             @RequestParam("objectName") String objectName
-//            @RequestBody @Validated MinioParameter minioParameter
     ) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
         MinioUtil.uploadFromMultipartFile(
                 minioClient,
@@ -45,10 +45,11 @@ public class MinioController {
                 bucketName,
                 objectName
         );
+        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);
     }
 
     @RequestMapping("/download")
-    public void download(
+    public ResponseBodyVO<String> download(
             @RequestBody @Validated MinioParameter minioParameter,
             HttpServletResponse response
     ) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
@@ -59,6 +60,7 @@ public class MinioController {
         );
         String fileName = FileUtil.getFileName(minioParameter.getObjectName());
         FileUtil.downloadForHttp(fileName, inputStream, response, 1024);
+        return new ResponseBodyVO<>(ResponseBodyVO.Response.SUCCESS);
     }
 
 }

+ 11 - 0
simulation-resource-scheduler/pom.xml

@@ -56,6 +56,17 @@
         </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>
+        <!-- 权限认证 - 结束 -->
+
         <!-- nacos - 开始 -->
         <dependency>
             <groupId>org.springframework.cloud</groupId>

+ 2 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/SimulationResourceSchedulerApplication.java

@@ -3,10 +3,12 @@ package com.css.simulation.resource.scheduler;
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cloud.openfeign.EnableFeignClients;
+import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
 
 
 @SpringBootApplication
 @EnableFeignClients
+@EnableResourceServer
 public class SimulationResourceSchedulerApplication {
 
     public static void main(String[] args) {

+ 55 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/configuration/oauth/MyTokenServices.java

@@ -0,0 +1,55 @@
+package com.css.simulation.resource.scheduler.configuration.oauth;
+
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
+import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
+
+import javax.annotation.Resource;
+
+@Configuration
+public class MyTokenServices {
+
+    @Resource
+    private OauthParameter oauthParameter;
+
+
+    /**
+     * access_token 验证策略
+     * DefaultTokenServices()
+     * RemoteTokenServices():远程验证,通过 /oauth/check_token
+     * SpringSocialTokenServices()
+     * UserInfoTokenServices()
+     */
+    @Bean
+    public ResourceServerTokenServices tokenServices() {
+        RemoteTokenServices services = new RemoteTokenServices();
+        services.setCheckTokenEndpointUrl(oauthParameter.getCheckTokenEndpointUrl());  // 需要在授权服务器公开 /oauth/check_token
+        services.setClientId(oauthParameter.getClientId());
+        services.setClientSecret(oauthParameter.getClientSecret());
+        return services;
+    }
+
+//* -------------------------------- 使用 jwt 令牌,无需访问远程授权服务器,也可以两者结合 --------------------------------
+//    /**
+//     * 令牌存储
+//     * <p>
+//     * (推荐)new JwtTokenStore():基于 Jwt
+//     * (推荐)new RedisTokenStore():基于 redis
+//     * new InMemoryTokenStore():基于内存
+//     * new JwkTokenStore():基于 Jwk
+//     * new JdbcTokenStore():基于 Jdbc
+//     */
+//    @Bean
+//    public TokenStore tokenStore() {
+////        return new InMemoryTokenStore();
+//        return new JwtTokenStore(accessTokenConverter());
+//    }
+//
+//    @Bean
+//    public JwtAccessTokenConverter accessTokenConverter() {
+//        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
+//        jwtAccessTokenConverter.setSigningKey("project");
+//        return jwtAccessTokenConverter;
+//    }
+}

+ 41 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/configuration/oauth/OAuth2ResourceServerConfiguration.java

@@ -0,0 +1,41 @@
+package com.css.simulation.resource.scheduler.configuration.oauth;
+
+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.ResourceServerConfigurerAdapter;
+import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
+import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
+
+import javax.annotation.Resource;
+
+@Configuration
+public class OAuth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
+
+
+    @Resource
+    private OauthParameter oauthParameter;
+
+    @Resource
+    private ResourceServerTokenServices resourceServerTokenServices;
+
+    @Override
+    public void configure(ResourceServerSecurityConfigurer resources) {
+        resources.resourceId(oauthParameter.getResourceId())      // 资源 id
+                .tokenServices(resourceServerTokenServices)    // 使用远程服务验证令牌的服务
+                .stateless(true);   // 无状态模式,即无需用户登录,无 session
+    }
+
+    /**
+     * 配置拦截请求,通过 scope
+     */
+    @Override
+    public void configure(HttpSecurity http) throws Exception {
+        http.csrf().disable()   // 禁用 csrf
+                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)// 无状态验证
+                .and()
+                .authorizeRequests().anyRequest()
+                .access("#oauth2.hasScope('all')") // 拦截所有请求判断 scope
+        ;
+    }
+}

+ 16 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/configuration/oauth/OauthParameter.java

@@ -0,0 +1,16 @@
+package com.css.simulation.resource.scheduler.configuration.oauth;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+
+@Data
+@Component
+@ConfigurationProperties(prefix="oauth")
+public class OauthParameter {
+
+    private String resourceId;
+    private String checkTokenEndpointUrl;
+    private String clientId;
+    private String clientSecret;
+}

+ 84 - 84
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/configuration/redis/RedisTemplateConfiguration.java

@@ -1,84 +1,84 @@
-package com.css.simulation.resource.scheduler.configuration.redis;
-
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
-import org.springframework.cache.CacheManager;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.data.redis.cache.RedisCacheConfiguration;
-import org.springframework.data.redis.cache.RedisCacheManager;
-import org.springframework.data.redis.connection.RedisConnectionFactory;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
-import org.springframework.data.redis.serializer.RedisSerializationContext;
-import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-import java.time.Duration;
-import java.util.HashMap;
-import java.util.Map;
-
-@Configuration
-@EnableCaching
-public class RedisTemplateConfiguration {
-
-    @Bean
-    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
-        // 使用 Jackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value 值。
-        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
-        ObjectMapper mapper = new ObjectMapper();
-        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
-        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
-        // 指定序列化输入的类型,类必须是非 final 修饰的,final修饰的类,比如 String, Integer 等会跑出异常
-        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
-        serializer.setObjectMapper(mapper);
-        return serializer;
-    }
-
-    @Bean
-    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
-        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
-        configuration = configuration
-                // 设置 key 为 string 序列化
-                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
-                // 设置 value 为 json 序列化
-                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
-                // 不缓存空值
-                .disableCachingNullValues()
-                // 设置缓存默认过期时间(30 分钟)
-                .entryTtl(Duration.ofMinutes(30L))
-        ;
-        // 特殊缓存空间应用不同的配置
-        Map<String, RedisCacheConfiguration> map = new HashMap<>();
-        map.put("miFirst", configuration.entryTtl(Duration.ofMinutes(30L)));
-        map.put("miSecond", configuration.entryTtl(Duration.ofHours(1L)));
-
-        return RedisCacheManager.builder(connectionFactory)
-                .cacheDefaults(configuration)           // 默认配置
-                .withInitialCacheConfigurations(map)    // 特殊缓存
-                .transactionAware()                     // 事务
-                .build();
-    }
-
-    @Bean
-    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
-        RedisTemplate<String, Object> template = new RedisTemplate<>();
-        template.setConnectionFactory(connectionFactory);
-        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
-        // key 采用 String 的序列化方式
-        template.setKeySerializer(stringRedisSerializer);
-        // hash 的 key 采用 String 的序列化方式
-        template.setHashKeySerializer(stringRedisSerializer);
-        // value 采用 jackson 的序列化方式
-        template.setValueSerializer(jackson2JsonRedisSerializer());
-        // hash 的 value 采用 jackson 的序列化方式
-        template.setHashValueSerializer(jackson2JsonRedisSerializer());
-        template.afterPropertiesSet();
-        return template;
-    }
-
-
-}
+//package com.css.simulation.resource.scheduler.configuration.redis;
+//
+//import com.fasterxml.jackson.annotation.JsonAutoDetect;
+//import com.fasterxml.jackson.annotation.PropertyAccessor;
+//import com.fasterxml.jackson.databind.ObjectMapper;
+//import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
+//import org.springframework.cache.CacheManager;
+//import org.springframework.cache.annotation.EnableCaching;
+//import org.springframework.context.annotation.Bean;
+//import org.springframework.context.annotation.Configuration;
+//import org.springframework.data.redis.cache.RedisCacheConfiguration;
+//import org.springframework.data.redis.cache.RedisCacheManager;
+//import org.springframework.data.redis.connection.RedisConnectionFactory;
+//import org.springframework.data.redis.core.RedisTemplate;
+//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+//import org.springframework.data.redis.serializer.RedisSerializationContext;
+//import org.springframework.data.redis.serializer.RedisSerializer;
+//import org.springframework.data.redis.serializer.StringRedisSerializer;
+//
+//import java.time.Duration;
+//import java.util.HashMap;
+//import java.util.Map;
+//
+//@Configuration
+//@EnableCaching
+//public class RedisTemplateConfiguration {
+//
+//    @Bean
+//    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
+//        // 使用 Jackson2JsonRedisSerializer 来序列化和反序列化 redis 的 value 值。
+//        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
+//        ObjectMapper mapper = new ObjectMapper();
+//        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
+//        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+//        // 指定序列化输入的类型,类必须是非 final 修饰的,final修饰的类,比如 String, Integer 等会跑出异常
+//        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
+//        serializer.setObjectMapper(mapper);
+//        return serializer;
+//    }
+//
+//    @Bean
+//    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
+//        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
+//        configuration = configuration
+//                // 设置 key 为 string 序列化
+//                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
+//                // 设置 value 为 json 序列化
+//                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
+//                // 不缓存空值
+//                .disableCachingNullValues()
+//                // 设置缓存默认过期时间(30 分钟)
+//                .entryTtl(Duration.ofMinutes(30L))
+//        ;
+//        // 特殊缓存空间应用不同的配置
+//        Map<String, RedisCacheConfiguration> map = new HashMap<>();
+//        map.put("miFirst", configuration.entryTtl(Duration.ofMinutes(30L)));
+//        map.put("miSecond", configuration.entryTtl(Duration.ofHours(1L)));
+//
+//        return RedisCacheManager.builder(connectionFactory)
+//                .cacheDefaults(configuration)           // 默认配置
+//                .withInitialCacheConfigurations(map)    // 特殊缓存
+//                .transactionAware()                     // 事务
+//                .build();
+//    }
+//
+//    @Bean
+//    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
+//        RedisTemplate<String, Object> template = new RedisTemplate<>();
+//        template.setConnectionFactory(connectionFactory);
+//        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
+//        // key 采用 String 的序列化方式
+//        template.setKeySerializer(stringRedisSerializer);
+//        // hash 的 key 采用 String 的序列化方式
+//        template.setHashKeySerializer(stringRedisSerializer);
+//        // value 采用 jackson 的序列化方式
+//        template.setValueSerializer(jackson2JsonRedisSerializer());
+//        // hash 的 value 采用 jackson 的序列化方式
+//        template.setHashValueSerializer(jackson2JsonRedisSerializer());
+//        template.afterPropertiesSet();
+//        return template;
+//    }
+//
+//
+//}

+ 25 - 0
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/feign/DemoController.java

@@ -0,0 +1,25 @@
+package com.css.simulation.resource.scheduler.feign;
+
+import api.common.pojo.common.ResponseBodyVO;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import javax.annotation.Resource;
+
+@RestController
+public class DemoController {
+
+    @Resource
+    private DemoService demoService;
+
+    @RequestMapping("/upload")
+    public ResponseBodyVO<String> upload(
+            @RequestParam("file") MultipartFile multipartFile,
+            @RequestParam("bucketName") String bucketName,
+            @RequestParam("objectName") String objectName
+    ) {
+        return demoService.upload(multipartFile, bucketName, objectName);
+    }
+}

+ 4 - 2
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/feign/DemoService.java

@@ -1,15 +1,17 @@
 package com.css.simulation.resource.scheduler.feign;
 
+import api.common.pojo.common.ResponseBodyVO;
 import com.css.simulation.resource.scheduler.configuration.feign.FeignConfiguration;
 import com.css.simulation.resource.scheduler.feign.fallback.DemoServiceFallback;
 import org.springframework.cloud.openfeign.FeignClient;
 import org.springframework.stereotype.Component;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.multipart.MultipartFile;
 
 @Component
 @FeignClient(value = "simulation-resource-common", fallback = DemoServiceFallback.class, configuration = FeignConfiguration.class)
 public interface DemoService {
 
-    @RequestMapping("/hello")
-    String hello();
+    @RequestMapping("/simulation/resource/common")
+    ResponseBodyVO<String> upload(MultipartFile multipartFile, String bucketName, String objectName);
 }

+ 5 - 2
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/feign/fallback/DemoServiceFallback.java

@@ -1,10 +1,13 @@
 package com.css.simulation.resource.scheduler.feign.fallback;
 
+import api.common.pojo.common.ResponseBodyVO;
 import com.css.simulation.resource.scheduler.feign.DemoService;
+import org.springframework.web.multipart.MultipartFile;
 
 public class DemoServiceFallback implements DemoService {
+
     @Override
-    public String hello() {
-        return "服务错误!";
+    public ResponseBodyVO<String> upload(MultipartFile multipartFile, String bucketName, String objectName) {
+        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE);
     }
 }

+ 2 - 5
simulation-resource-scheduler/src/main/java/com/css/simulation/resource/scheduler/service/TaskService.java

@@ -1,16 +1,13 @@
 package com.css.simulation.resource.scheduler.service;
 
 import api.common.pojo.common.ResponseBodyVO;
-import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 
-import javax.annotation.Resource;
-
 @Service
 public class TaskService {
 
-    @Resource
-    private RedisTemplate<String, String> redisTemplate;
+//    @Resource
+//    private RedisTemplate<String, String> redisTemplate;
 
 
     /**

+ 0 - 5
simulation-resource-scheduler/src/main/resources/bootstrap.yml

@@ -1,8 +1,3 @@
-server:
-  port: 8001
-  servlet:
-    context-path: /simulation/resource/scheduler
-
 spring:
   application:
     name: simulation-resource-scheduler