Procházet zdrojové kódy

权限认证调整修改

rengb před 3 roky
rodič
revize
fb7c5427e6
38 změnil soubory, kde provedl 364 přidání a 1941 odebrání
  1. 3 8
      common/src/main/java/com/lantone/common/constant/AuthConstant.java
  2. 1 4
      gateway-service/src/main/java/com/lantone/authorization/AuthorizationManager.java
  3. 13 1
      gateway-service/src/main/resources/bootstrap.yml
  4. 2 2
      security-center/src/main/java/com/lantone/SecurityCenterApplication.java
  5. 0 1
      security-center/src/main/java/com/lantone/security/client/AuthServiceClient.java
  6. 0 1
      security-center/src/main/java/com/lantone/security/client/hystrix/AuthServiceHystrix.java
  7. 23 0
      security-center/src/main/java/com/lantone/security/component/ResourceRoleRulesHolder.java
  8. 0 19
      security-center/src/main/java/com/lantone/security/config/CustomAccessTokenConverter.java
  9. 0 31
      security-center/src/main/java/com/lantone/security/config/CustomTokenEnhancer.java
  10. 0 17
      security-center/src/main/java/com/lantone/security/config/GlobalMethodSecurityConfigurer.java
  11. 0 89
      security-center/src/main/java/com/lantone/security/config/OAuth2Configurer.java
  12. 13 0
      security-center/src/main/java/com/lantone/security/config/RedisConfig.java
  13. 0 202
      security-center/src/main/java/com/lantone/security/config/RedisConfigurer.java
  14. 0 267
      security-center/src/main/java/com/lantone/security/config/ResourceServerConfigurer.java
  15. 0 69
      security-center/src/main/java/com/lantone/security/config/WebSecurityConfigurer.java
  16. 0 75
      security-center/src/main/java/com/lantone/security/dto/JWT.java
  17. 0 27
      security-center/src/main/java/com/lantone/security/dto/JwtDTO.java
  18. 0 16
      security-center/src/main/java/com/lantone/security/dto/JwtStore.java
  19. 0 131
      security-center/src/main/java/com/lantone/security/entity/SysUserUaa.java
  20. 0 21
      security-center/src/main/java/com/lantone/security/entity/Token.java
  21. 0 83
      security-center/src/main/java/com/lantone/security/exception/CommonExceptionHandler.java
  22. 0 51
      security-center/src/main/java/com/lantone/security/exception/ServiceErrorCode.java
  23. 0 13
      security-center/src/main/java/com/lantone/security/facade/TokenFacade.java
  24. 35 0
      security-center/src/main/java/com/lantone/security/facade/UserAdminFacade.java
  25. 135 141
      security-center/src/main/java/com/lantone/security/facade/UserLoginFacade.java
  26. 21 0
      security-center/src/main/java/com/lantone/security/service/AuthService.java
  27. 0 55
      security-center/src/main/java/com/lantone/security/service/SysTokenService.java
  28. 0 40
      security-center/src/main/java/com/lantone/security/service/UrlGrantedAuthority.java
  29. 0 64
      security-center/src/main/java/com/lantone/security/service/UrlUserService.java
  30. 0 196
      security-center/src/main/java/com/lantone/security/service/impl/SysTokenServiceImpl.java
  31. 0 85
      security-center/src/main/java/com/lantone/security/util/SysJwtUtil.java
  32. 0 106
      security-center/src/main/java/com/lantone/security/util/SysUserUtils.java
  33. 26 0
      security-center/src/main/java/com/lantone/security/vo/LoginVO.java
  34. 0 18
      security-center/src/main/java/com/lantone/security/vo/SysUserBaseVO.java
  35. 0 20
      security-center/src/main/java/com/lantone/security/vo/UserLoginNoPassVO.java
  36. 43 0
      security-center/src/main/java/com/lantone/security/web/UserAdminController.java
  37. 48 87
      security-center/src/main/java/com/lantone/security/web/UserLoginController.java
  38. 1 1
      user-auth/src/main/java/com/lantone/userauth/service/impl/UserServiceImpl.java

+ 3 - 8
common/src/main/java/com/lantone/common/constant/AuthConstant.java

@@ -18,19 +18,14 @@ public interface AuthConstant {
     String AUTHORITY_CLAIM_NAME = "authorities";
 
     /**
-     * 后台管理client_id
+     * 用户处理中心client_id
      */
-    String ADMIN_CLIENT_ID = "admin-app";
-
-    /**
-     * 前台商城client_id
-     */
-    String PORTAL_CLIENT_ID = "portal-app";
+    String USER_ADMIN_CLIENT_ID = "security-center";
 
     /**
      * 后台管理接口路径匹配
      */
-    String ADMIN_URL_PATTERN = "/mall-admin/**";
+    String ADMIN_URL_PATTERN = "/security/**";
 
     /**
      * Redis缓存权限规则key

+ 1 - 4
gateway-service/src/main/java/com/lantone/authorization/AuthorizationManager.java

@@ -68,10 +68,7 @@ public class AuthorizationManager implements ReactiveAuthorizationManager<Author
             JWSObject jwsObject = JWSObject.parse(realToken);
             String userStr = jwsObject.getPayload().toString();
             UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
-            if (AuthConstant.ADMIN_CLIENT_ID.equals(userDto.getClientId()) && !pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uri.getPath())) {
-                return Mono.just(new AuthorizationDecision(false));
-            }
-            if (AuthConstant.PORTAL_CLIENT_ID.equals(userDto.getClientId()) && pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uri.getPath())) {
+            if (AuthConstant.USER_ADMIN_CLIENT_ID.equals(userDto.getClientId()) && !pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uri.getPath())) {
                 return Mono.just(new AuthorizationDecision(false));
             }
         } catch (ParseException e) {

+ 13 - 1
gateway-service/src/main/resources/bootstrap.yml

@@ -8,6 +8,10 @@ spring:
     user:
       name: admin
       password: lantone
+    oauth2:
+      resourceserver:
+        jwt:
+          jwk-set-uri: 'http://localhost:8860/userauth/rsa/publicKey' #配置RSA的公钥访问地址
   cloud:
     gateway:
       discovery:
@@ -27,6 +31,12 @@ spring:
             - Path=/security/**
           filters:
             - StripPrefix=1
+        - id: user-auth
+          uri: lb://user-auth
+          predicates:
+            - Path=/userauth/**
+          filters:
+            - StripPrefix=1
   #redis
   redis:
     database:
@@ -73,4 +83,6 @@ secure:
       - "/**/*.png"
       - "/**/*.ico"
       - "/webjars/springfox-swagger-ui/**"
-      - "/actuator/**"
+      - "/actuator/**"
+      - "/userauthh/oauth/token"
+      - "/userauth/rsa/publicKey"

+ 2 - 2
security-center/src/main/java/com/lantone/SecurityCenterApplication.java

@@ -5,13 +5,13 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
 import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
 import org.springframework.cloud.openfeign.EnableFeignClients;
 
-@SpringBootApplication
 @EnableEurekaClient
 @EnableFeignClients
+@SpringBootApplication
 public class SecurityCenterApplication {
 
     public static void main(String[] args) {
         SpringApplication.run(SecurityCenterApplication.class, args);
     }
 
-}
+}

+ 0 - 1
security-center/src/main/java/com/lantone/security/client/AuthServiceClient.java

@@ -1,7 +1,6 @@
 package com.lantone.security.client;
 
 import com.lantone.security.client.hystrix.AuthServiceHystrix;
-import com.lantone.security.dto.JWT;
 import org.springframework.cloud.openfeign.FeignClient;
 import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.web.bind.annotation.PostMapping;

+ 0 - 1
security-center/src/main/java/com/lantone/security/client/hystrix/AuthServiceHystrix.java

@@ -2,7 +2,6 @@ package com.lantone.security.client.hystrix;
 
 
 import com.lantone.security.client.AuthServiceClient;
-import com.lantone.security.dto.JWT;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.security.oauth2.common.OAuth2AccessToken;
 import org.springframework.stereotype.Component;

+ 23 - 0
security-center/src/main/java/com/lantone/security/component/ResourceRoleRulesHolder.java

@@ -0,0 +1,23 @@
+package com.lantone.security.component;
+
+import org.springframework.stereotype.Component;
+
+import javax.annotation.PostConstruct;
+
+/**
+ * @Description: 资源与角色访问对应关系操作组件
+ * @author: rengb
+ * @time: 2021/1/5 18:27
+ */
+@Component
+public class ResourceRoleRulesHolder {
+
+    /**
+     * 预加载所有权限
+     */
+    @PostConstruct
+    public void initResourceRolesMap() {
+
+    }
+
+}

+ 0 - 19
security-center/src/main/java/com/lantone/security/config/CustomAccessTokenConverter.java

@@ -1,19 +0,0 @@
-package com.lantone.security.config;
-
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
-import org.springframework.stereotype.Component;
-
-import java.util.Map;
-
-@Component
-public class CustomAccessTokenConverter extends DefaultAccessTokenConverter {
-
-    @Override
-    public OAuth2Authentication extractAuthentication(Map<String, ?> claims) {
-        OAuth2Authentication authentication = super.extractAuthentication(claims);
-        authentication.setDetails(claims);
-        return authentication;
-    }
-
-}

+ 0 - 31
security-center/src/main/java/com/lantone/security/config/CustomTokenEnhancer.java

@@ -1,31 +0,0 @@
-package com.lantone.security.config;
-
-import com.lantone.security.entity.SysUserUaa;
-import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.security.oauth2.provider.OAuth2Authentication;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @Description: token生成携带的信息
- * @author: gaodm
- * @time: 2018/9/3 15:16
- */
-public class CustomTokenEnhancer implements TokenEnhancer {
-
-    @Override
-    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
-        final Map<String, Object> additionalInfo = new HashMap<>();
-        SysUserUaa user = (SysUserUaa) authentication.getUserAuthentication().getPrincipal();
-        additionalInfo.put("user_id", user.getId());
-        additionalInfo.put("hosp_id", user.getHospitalId());
-        additionalInfo.put("functionAuthorities", user.getFunctionAuthorities());
-        //		additionalInfo.put("authorities", user.getAuthorities());
-        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
-        return accessToken;
-    }
-
-}

+ 0 - 17
security-center/src/main/java/com/lantone/security/config/GlobalMethodSecurityConfigurer.java

@@ -1,17 +0,0 @@
-package com.lantone.security.config;
-
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
-
-/**
- * @Description: 安全配置类
- * Spring Security默认是禁用注解的,要想开启注解,需要在继承WebSecurityConfigurerAdapter的类上
- * 加@EnableGlobalMethodSecurity注解,并在该类中将AuthenticationManager定义为Bean。
- * @author: gaodm
- * @time: 2018/8/2 13:38
- */
-@Configuration
-@EnableGlobalMethodSecurity(prePostEnabled = true)
-public class GlobalMethodSecurityConfigurer {
-
-}

+ 0 - 89
security-center/src/main/java/com/lantone/security/config/OAuth2Configurer.java

@@ -1,89 +0,0 @@
-package com.lantone.security.config;
-
-import com.lantone.security.service.UrlUserService;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
-import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
-import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
-import org.springframework.security.oauth2.provider.token.TokenEnhancer;
-import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
-import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
-import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
-import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
-
-import java.util.Arrays;
-
-/**
- * @Description: OAuth2授权认证配置类 指定认证管理器、token内容、指定oauth2配置给谁发令牌,设置令牌的有效时间
- * @author: gaodm
- * @time: 2018/8/2 14:24
- */
-@Configuration
-@EnableAuthorizationServer
-@Slf4j
-public class OAuth2Configurer extends AuthorizationServerConfigurerAdapter {
-    @Autowired
-    private UrlUserService urlUserService;
-
-    @Override
-    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
-        clients.inMemory()
-                .withClient("uaa-service")
-                .secret("{noop}123456")
-                .scopes("service")
-                .autoApprove(true)
-                .authorizedGrantTypes("implicit", "refresh_token", "password", "authorization_code")
-                .accessTokenValiditySeconds(24 * 3600)
-                .refreshTokenValiditySeconds(30 * 24 * 3600);
-    }
-
-    /**
-     * 注入自定义token生成方式
-     *
-     * @return
-     */
-    @Bean
-    public TokenEnhancer customerEnhancer() {
-        return new CustomTokenEnhancer();
-    }
-
-    @Override
-    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
-        //指定认证管理器
-        endpoints.authenticationManager(authenticationManager).userDetailsService(urlUserService);
-        //指定token存储位置
-        endpoints.tokenStore(new JwtTokenStore(jwtTokenEnhancerServer()));
-        // 自定义token生成方式
-        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
-        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customerEnhancer(), jwtTokenEnhancerServer()));
-        endpoints.tokenEnhancer(tokenEnhancerChain);
-    }
-
-    @Override
-    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
-        security.tokenKeyAccess("permitAll()")
-                .checkTokenAccess("isAuthenticated()")
-                .allowFormAuthenticationForClients();
-    }
-
-    @Autowired
-    @Qualifier("authenticationManagerBean")
-    private AuthenticationManager authenticationManager;
-
-    @Bean("JwtTokenEnhancerServer")
-    protected JwtAccessTokenConverter jwtTokenEnhancerServer() {
-        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("diagbot-jwt.jks"), "diagbot123456".toCharArray());
-        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
-        converter.setKeyPair(keyStoreKeyFactory.getKeyPair("diagbot-jwt"));
-        log.info("Created jwtTokenEnhancerServer success");
-        return converter;
-    }
-}

+ 13 - 0
security-center/src/main/java/com/lantone/security/config/RedisConfig.java

@@ -0,0 +1,13 @@
+package com.lantone.security.config;
+
+import com.lantone.common.config.BaseRedisConfig;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * Redis相关配置
+ * Created by macro on 2020/6/19.
+ */
+@Configuration
+public class RedisConfig extends BaseRedisConfig {
+
+}

+ 0 - 202
security-center/src/main/java/com/lantone/security/config/RedisConfigurer.java

@@ -1,202 +0,0 @@
-package com.lantone.security.config;
-
-import com.fasterxml.jackson.annotation.JsonAutoDetect;
-import com.fasterxml.jackson.annotation.PropertyAccessor;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.cache.CacheManager;
-import org.springframework.cache.annotation.CachingConfigurerSupport;
-import org.springframework.cache.annotation.EnableCaching;
-import org.springframework.cache.interceptor.KeyGenerator;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.Primary;
-import org.springframework.data.redis.cache.RedisCacheConfiguration;
-import org.springframework.data.redis.cache.RedisCacheManager;
-import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
-import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
-import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
-import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
-import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
-import org.springframework.data.redis.serializer.RedisSerializationContext;
-import org.springframework.data.redis.serializer.StringRedisSerializer;
-
-import java.time.Duration;
-
-@Configuration
-@EnableCaching
-@Slf4j
-public class RedisConfigurer extends CachingConfigurerSupport {
-
-    @Value("${spring.redis.database.cache}")
-    private String databaseCache;
-    @Value("${spring.redis.database.token}")
-    private String databaseMr;
-    @Value("${spring.redis.host}")
-    private String host;
-    @Value("${spring.redis.password}")
-    private String password;
-    @Value("${spring.redis.port}")
-    private int port;
-    @Value("${spring.redis.timeout}")
-    private int timeout;
-    @Value("${spring.redis.lettuce.pool.max-active}")
-    private int maxActive;
-    @Value("${spring.redis.lettuce.pool.max-idle}")
-    private int maxIdle;
-    @Value("${spring.redis.lettuce.pool.max-wait}")
-    private long maxWaitMillis;
-    @Value("${spring.redis.lettuce.pool.min-idle}")
-    private int minIdle;
-
-    @Autowired
-    @Qualifier("factoryForCache")
-    private LettuceConnectionFactory lettuceConnectionFactory;
-
-    @Bean
-    public GenericObjectPoolConfig getRedisConfig() {
-        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
-        poolConfig.setMaxTotal(maxActive);
-        poolConfig.setMaxIdle(maxIdle);
-        poolConfig.setMaxWaitMillis(maxWaitMillis);
-        poolConfig.setMinIdle(minIdle);
-        return poolConfig;
-    }
-
-    @Bean
-    @Override
-    public CacheManager cacheManager() {
-        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
-                // 设置 key为string序列化
-                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
-                // 设置value为json序列化
-                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getSerializer()))
-                // 不缓存空值
-                .disableCachingNullValues();
-        RedisCacheManager cacheManager = RedisCacheManager.builder(lettuceConnectionFactory)
-                .cacheDefaults(redisCacheConfiguration)
-                .transactionAware()
-                .build();
-        cacheManager.afterPropertiesSet();
-        log.info("RedisCacheManager config success");
-        return cacheManager;
-    }
-
-    @Bean(name = "springSessionDefaultRedisSerializer")
-    public GenericJackson2JsonRedisSerializer getGenericJackson2JsonRedisSerializer() {
-        return new GenericJackson2JsonRedisSerializer();
-    }
-
-    /**
-     * 缓存使用的redis
-     *
-     * @return
-     */
-    @Bean("factoryForCache")
-    @Primary
-    public LettuceConnectionFactory redisConnectionFactory() {
-        return getRedisConnectionFactory(Integer.valueOf(databaseCache));
-    }
-
-    @Bean
-    public RedisTemplate<String, Object> redisTemplate() {
-        return getRedisTemplate(lettuceConnectionFactory);
-    }
-
-    private Jackson2JsonRedisSerializer getSerializer() {
-        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
-        ObjectMapper om = new ObjectMapper();
-        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
-        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
-        jackson2JsonRedisSerializer.setObjectMapper(om);
-        return jackson2JsonRedisSerializer;
-    }
-
-    @Bean
-    @Override
-    public KeyGenerator keyGenerator() {
-        //  设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存
-        // 使用:进行分割,可以很多显示出层级关系
-        // 这里其实就是new了一个KeyGenerator对象
-        return (target, method, params) -> {
-            StringBuilder sb = new StringBuilder();
-            sb.append(target.getClass().getName());
-            sb.append(":");
-            sb.append(method.getName());
-            for (Object obj : params) {
-                sb.append(":" + String.valueOf(obj));
-            }
-            String rsToUse = String.valueOf(sb);
-            log.info("自动生成Redis Key -> [{}]", rsToUse);
-            return rsToUse;
-        };
-    }
-
-    /**
-     * Token使用的redis
-     *
-     * @return
-     */
-    @Bean("factoryForToken")
-    public LettuceConnectionFactory redisConnectionFactoryForToken() {
-        return getRedisConnectionFactory(Integer.valueOf(databaseMr));
-    }
-
-    @Bean(name = "redisTemplateForToken")
-    public RedisTemplate<String, Object> redisTemplateForToken(@Qualifier("factoryForToken") LettuceConnectionFactory factory) {
-        return getRedisTemplate(factory);
-    }
-
-    /**
-     * 表字段和注释使用的redis
-     *
-     * @return
-     */
-    @Bean("factoryForTable")
-    public LettuceConnectionFactory redisConnectionFactoryForTable() {
-        return getRedisConnectionFactory(Integer.valueOf(databaseMr));
-    }
-
-    @Bean(name = "redisTemplateForTable")
-    public RedisTemplate<String, Object> redisTemplateForTable(@Qualifier("factoryForTable") LettuceConnectionFactory factory) {
-        return getRedisTemplate(factory);
-    }
-
-
-    private LettuceConnectionFactory getRedisConnectionFactory(Integer database) {
-        RedisStandaloneConfiguration connection = new RedisStandaloneConfiguration();
-        connection.setHostName(host);
-        connection.setPort(port);
-        connection.setPassword(password);
-        connection.setDatabase(database);
-        GenericObjectPoolConfig poolConfig = getRedisConfig();
-        LettuceClientConfiguration builder = LettucePoolingClientConfiguration.builder()
-                .commandTimeout(Duration.ofMillis(timeout))
-                .poolConfig(poolConfig)
-                .shutdownTimeout(Duration.ZERO)
-                .build();
-        LettuceConnectionFactory factory = new LettuceConnectionFactory(connection, builder);
-        return factory;
-    }
-
-    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
-        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
-        redisTemplate.setConnectionFactory(factory);
-
-        // value值的序列化
-        redisTemplate.setValueSerializer(getSerializer());
-        redisTemplate.setHashValueSerializer(getSerializer());
-        // key的序列化采用StringRedisSerializer
-        redisTemplate.setKeySerializer(new StringRedisSerializer());
-        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
-        redisTemplate.afterPropertiesSet();
-        return redisTemplate;
-    }
-}
- 

+ 0 - 267
security-center/src/main/java/com/lantone/security/config/ResourceServerConfigurer.java

@@ -1,267 +0,0 @@
-package com.lantone.security.config;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.ComponentScan;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.core.io.ClassPathResource;
-import org.springframework.core.io.Resource;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.jwt.crypto.sign.RsaVerifier;
-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.store.JwtAccessTokenConverter;
-import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
-import org.springframework.util.FileCopyUtils;
-
-import java.io.IOException;
-
-/**
- * @Description: 权限资源配置类
- * @author: gaodm
- * @time: 2018/8/2 14:21
- */
-@Configuration
-@EnableResourceServer
-@ComponentScan({"com.lantone.security.config"})
-public class ResourceServerConfigurer extends ResourceServerConfigurerAdapter {
-    Logger log = LoggerFactory.getLogger(ResourceServerConfigurer.class);
-
-    @Override
-    public void configure(HttpSecurity http) throws Exception {
-        http.cors()
-                .and()
-                .csrf().disable()
-                .authorizeRequests()
-                .regexMatchers(".*swagger.*", ".*v2.*", ".*webjars.*", "/druid.*", "/actuator.*", "/hystrix.*").permitAll()
-                .antMatchers("/sys/user/getJwt").permitAll()
-                .antMatchers("/sys/user/getJwtNoPass").permitAll()
-                .antMatchers("/sys/user/refreshJwt").permitAll()
-                .antMatchers("/sys/user/checkToken").permitAll()
-                .antMatchers("/sys/dictionaryInfo/getDictionary").permitAll()
-                .antMatchers("/oauth/token").permitAll()
-                .antMatchers("/oauth/check_token").permitAll()
-                .antMatchers("/cache/clear").permitAll()
-                .antMatchers("/qc/behospitalInfo/execule").permitAll()
-                .antMatchers("/qc/behospitalInfo/analyze_rpc").permitAll()
-                .antMatchers("/qc/behospitalInfo/analyze_api").permitAll()
-                .antMatchers("/qc/behospitalInfo/analyze_run").permitAll()
-                .antMatchers("/qc/module/getById").permitAll()
-                .antMatchers("/qc/module/getModuleMap").permitAll()
-                .antMatchers("/qc/cases/getQcCases").permitAll()
-                .antMatchers("/qc/behospitalInfo/page").permitAll()
-                .antMatchers("/qc/casesEntryHospital/getQcCasesEntryAll").permitAll()
-                .antMatchers("/qc/casesEntryHospital/getQcCasesAll").permitAll()
-                .antMatchers("/qc/behospitalInfo/getByBehospitalCode").permitAll()
-                .antMatchers("/bas/dept/getList").permitAll()
-                .antMatchers("/bas/dept/getListUser").permitAll()
-                .antMatchers("/qc/behospitalInfo/page_dept").permitAll()
-                .antMatchers("/qc/behospitalInfo/page_person").permitAll()
-                .antMatchers("/qc/behospitalInfo/page_group").permitAll()
-                .antMatchers("/qc/casesEntryHospital/findQcCasesEntry").permitAll()
-                .antMatchers("/qc/dataimport/import").permitAll()
-                .antMatchers("/qc/dataimport/test").permitAll()
-                .antMatchers("/qc/behospitalInfo/exportExcel").permitAll()
-                .antMatchers("/qc/behospitalInfo/exportQcresult").permitAll()
-                .antMatchers("/qc/behospitalInfo/exportQcresultByDept").permitAll()
-                .antMatchers("/qc/behospitalInfo/exportQcresultByGroup").permitAll()
-                .antMatchers("/qc/abnormal/getQcAnnormalMode").permitAll()
-                .antMatchers("/qc/dataimport/import").permitAll()
-                .antMatchers("/qc/dataimport/dataimportPrepare").permitAll()
-                .antMatchers("/qc/dataimport/test").permitAll()
-                .antMatchers("/sys/user/pageset/getPageSet").permitAll()
-                .antMatchers("/sys/user/pageset/savePageSet").permitAll()
-                .antMatchers("/sys/user/pageset/getDefultPageSet").permitAll()
-                .antMatchers("/consoleByDept/getDept").permitAll()
-                .antMatchers("/console/entryRejectPercent").permitAll()
-                .antMatchers("/console/qcResultLevelPercent").permitAll()
-                .antMatchers("/console/averageStatistics").permitAll()
-                .antMatchers("/console/entryByDept").permitAll()
-                .antMatchers("/console/entryCountGroupByCase").permitAll()
-                .antMatchers("/console/entryCountGroupByCasePage").permitAll()
-                .antMatchers("/console/entryCountGroupByEntry").permitAll()
-                .antMatchers("/console/entryCountGroupByEntryPage").permitAll()
-                .antMatchers("/console/entryGroupByEntryInnerPage").permitAll()
-                .antMatchers("/console/getAverageDayNum").permitAll()
-                .antMatchers("/console/getAverageDayNumPage").permitAll()
-                .antMatchers("/console/getAverageFee").permitAll()
-                .antMatchers("/console/getAverageFeePage").permitAll()
-                .antMatchers("/console/getAverageScore").permitAll()
-                .antMatchers("/console/getAverageScoreByDeptClass").permitAll()
-                .antMatchers("/console/getAverageScoreByDeptPage").permitAll()
-                .antMatchers("/console/getLevelResultDept").permitAll()
-                .antMatchers("/console/homePageLevelLimit").permitAll()
-                .antMatchers("/console/homePageLevelStatistics").permitAll()
-                .antMatchers("/console/leaveHosCount").permitAll()
-                .antMatchers("/console/medicalRecordIndicator").permitAll()
-                .antMatchers("/console/codingMonthly").permitAll()
-                .antMatchers("/console/levelPercentGroupByDeptPage").permitAll()
-                .antMatchers("/console/levelStatistics").permitAll()
-                .antMatchers("/console/levelStatisticsByDeptClass").permitAll()
-                .antMatchers("/console/mrCount").permitAll()
-                .antMatchers("/console/mrStatistics").permitAll()
-                .antMatchers("/console/qcResultShortPage").permitAll()
-                .antMatchers("/console/resultStatistics").permitAll()
-                .antMatchers("/console/resultStatisticsByDeptPage").permitAll()
-                .antMatchers("/console/homePageMRCount").permitAll()
-                .antMatchers("/console/qcCheckStatistics").permitAll()
-                .antMatchers("/console/unModifyMRStatistics").permitAll()
-                .antMatchers("/console/unModifyMRPage").permitAll()
-                .antMatchers("/console/reHos31DaysPage").permitAll()
-                .antMatchers("/console/beHosCount").permitAll()
-                .antMatchers("/console/casesEntryStatisticsById").permitAll()
-                .antMatchers("/console/hmImproveMRPage").permitAll()
-                .antMatchers("/console/qcCheckMRPage").permitAll()
-                .antMatchers("/consoleByDept/entryCountGroupByCaseAndDept").permitAll()
-                .antMatchers("/consoleByDept/entryCountGroupByCaseAndDeptPage").permitAll()
-                .antMatchers("/consoleByDept/entryCountGroupByEntryAndDept").permitAll()
-                .antMatchers("/consoleByDept/entryCountGroupByEntryAndDeptPage").permitAll()
-                .antMatchers("/consoleByDept/entryGroupByEntryAndDeptInnerPage").permitAll()
-                .antMatchers("/consoleByDept/homePageLevelByDeptLimit").permitAll()
-                .antMatchers("/consoleByDept/homePageLevelStatisticsByDept").permitAll()
-                .antMatchers("/consoleByDept/leaveHosCountByDept").permitAll()
-                .antMatchers("/consoleByDept/levelStatisticsByDept").permitAll()
-                .antMatchers("/consoleByDept/mrCountByDept").permitAll()
-                .antMatchers("/consoleByDept/qcResultShortByDeptPage").permitAll()
-                .antMatchers("/consoleByDept/resultStatisticsByDeptAndDoctorPage").permitAll()
-                .antMatchers("/console/export/homePageLevelExport").permitAll()
-                .antMatchers("/console/export/entryGroupByEntryExport").permitAll()
-                .antMatchers("/console/export/levelExport").permitAll()
-                .antMatchers("/console/entryStatistics").permitAll()
-                .antMatchers("/console/export/levelExport_TZ").permitAll()
-                .antMatchers("/console/export/getAverageDayNumExport").permitAll()
-                .antMatchers("/console/export/getAverageFeeExport").permitAll()
-                .antMatchers("/console/export/levelPercentGroupByDeptExport").permitAll()
-                .antMatchers("/console/export/entryCountGroupByEntryExport").permitAll()
-                .antMatchers("/console/export/entryCountGroupByCaseExport").permitAll()
-                .antMatchers("/console/export/entryStatisticsExport").permitAll()
-                .antMatchers("/console/export/qcResultShortPageExport").permitAll()
-                .antMatchers("/console/export/leaveHosMrPageExport").permitAll()
-                .antMatchers("/console/export/qcCheckStatisticsExport").permitAll()
-                .antMatchers("/console/export/unModifyMRPageExport").permitAll()
-                .antMatchers("/console/export/unModifyMRStatisticsExport").permitAll()
-                .antMatchers("/console/export/reHos31DaysPageExport").permitAll()
-                .antMatchers("/console/export/hmImproveMRPageExport").permitAll()
-                .antMatchers("/console/export/qcCheckMRPageExport").permitAll()
-                .antMatchers("/qc/data/sendDoctorInfos").permitAll()
-                .antMatchers("/qc/data/sendDeptInfos").permitAll()
-                .antMatchers("/qc/data/sendRecordTypes").permitAll()
-                .antMatchers("/qc/data/sendMrRecordIng").permitAll()
-                .antMatchers("/qc/data/sendMrContent").permitAll()
-                .antMatchers("/qc/data/sendMrRecord").permitAll()
-                .antMatchers("/qc/data/sendPatientInfo").permitAll()
-                .antMatchers("/qc/data/sendDoctorAdvice").permitAll()
-                .antMatchers("/qc/data/sendHomePageIng").permitAll()
-                .antMatchers("/qc/data/sendHomePage").permitAll()
-                .antMatchers("/qc/data/sendHomeDiagnose").permitAll()
-                .antMatchers("/qc/data/sendHomeOperation").permitAll()
-                .antMatchers("/qc/data/sendCrisis").permitAll()
-                .antMatchers("/qc/data/deleteFlag").permitAll()
-                .antMatchers("/qc/data/placeFile").permitAll()
-                .antMatchers("/qc/data/sendLisResults").permitAll()
-                .antMatchers("/qc/data/sendPacsResults").permitAll()
-                .antMatchers("/qc/data/getColumnZhAndCh").permitAll()
-                .antMatchers("/qc/data/analyseRec").permitAll()
-                .antMatchers("/qc/data/hisDataDeal").permitAll()
-                .antMatchers("/qc/data_str/sendAdmissionNote").permitAll()
-                .antMatchers("/qc/data_str/sendBloodResult").permitAll()
-                .antMatchers("/qc/data_str/sendBloodTransfusion").permitAll()
-                .antMatchers("/qc/data_str/sendConsultationApply").permitAll()
-                .antMatchers("/qc/data_str/sendConsultationNote").permitAll()
-                .antMatchers("/qc/data_str/sendConsultationRecord").permitAll()
-                .antMatchers("/qc/data_str/sendConsultationResult").permitAll()
-                .antMatchers("/qc/data_str/sendCrisisNote").permitAll()
-                .antMatchers("/qc/data_str/sendDeathDiscussion").permitAll()
-                .antMatchers("/qc/data_str/sendDeathNote").permitAll()
-                .antMatchers("/qc/data_str/sendDifficultCase").permitAll()
-                .antMatchers("/qc/data_str/sendFirstRecord").permitAll()
-                .antMatchers("/qc/data_str/sendIllCritically").permitAll()
-                .antMatchers("/qc/data_str/sendIllSeriousl").permitAll()
-                .antMatchers("/qc/data_str/sendLeaveHospital").permitAll()
-                .antMatchers("/qc/data_str/sendOperativeFirstRecord").permitAll()
-                .antMatchers("/qc/data_str/sendOperativeNote").permitAll()
-                .antMatchers("/qc/data_str/sendWardRecord").permitAll()
-                .antMatchers("/qc/data_str/sendTransferOutNote").permitAll()
-                .antMatchers("/qc/data_str/sendTransferInNote").permitAll()
-                .antMatchers("/qc/data_str/sendRescueNote").permitAll()
-                .antMatchers("/qc/data_str/sendPeriodConclusion").permitAll()
-                .antMatchers("/qc/data_str/sendPreoperativeDiscussion").permitAll()
-                .antMatchers("/qc/data_str/sendTalkInform").permitAll()
-                .antMatchers("/qc/data_str/sendInformedConsent").permitAll()
-                .antMatchers("/qc/data_str/sendContent").permitAll()
-                .antMatchers("/qc/doctoradvice/getPage").permitAll()
-                .antMatchers("/qc/medPacsInfo/getCheckPage").permitAll()
-                .antMatchers("/qc/medLisInfo/getExaminePage").permitAll()
-                .antMatchers("/qc/medLisInfo/getExamineSonPage").permitAll()
-                .antMatchers("/console/medicalCheckForm").permitAll()
-                .antMatchers("/qc/behospitalInfo/analyzeCds").permitAll()
-                .antMatchers("/console/medicalCheckTitle").permitAll()
-                .antMatchers("/console/export/medicalCheckExport").permitAll()
-                .antMatchers("/console/export/medicalCheckInnerExport").permitAll()
-                .antMatchers("/console/badLevelPage").permitAll()
-                .antMatchers("/console/export/badLevelPagePageExport").permitAll()
-                .antMatchers("/qc/medNurse/getMedNursePage").permitAll()
-                .antMatchers("/qc/behospitalInfo/exportQcresultByPerson").permitAll()
-                .antMatchers("/consoleByDept/beHosCountByDept").permitAll()
-                .antMatchers("/consoleByDept/casesEntryStatisticsByDept").permitAll()
-                .antMatchers("/bas/doctor/getList").permitAll()
-                .antMatchers("/consoleByDept/homePageOrGoodLevelByDept").permitAll()
-                .antMatchers("/print/export/homePageLevelExportByDept").permitAll()
-                .antMatchers("/print/export/homePageOrLevelExportByDept").permitAll()
-                .antMatchers("/print/export/entryGroupExportByDeptPage").permitAll()
-                .antMatchers("/print/export/entryGroupExportByDeptCase").permitAll()
-                .antMatchers("/print/export/entryGroupExportByDeptEntry").permitAll()
-                .antMatchers("/print/export/qcResultShortExportByDeptPage").permitAll()
-                .antMatchers("/print/export/levelExportByDept").permitAll()
-                .antMatchers("/consoleByDept/entryStatisticsByDept").permitAll()
-                .antMatchers("/print/export/entryStatisticsExportByDept").permitAll()
-                .antMatchers("/consoleByDept/leaveHosMRPageByDept").permitAll()
-                .antMatchers("/print/export/leaveHosMrPageExportByDept").permitAll()
-                .antMatchers("/consoleByDept/qcCheckStatisticsByDept").permitAll()
-                .antMatchers("/print/export/qcCheckStaExportByDept").permitAll()
-                .antMatchers("/consoleByDept/qcCheckMRPageByDept").permitAll()
-                .antMatchers("/print/export/qcCheckMRPageExportByDept").permitAll()
-                .antMatchers("/consoleByDept/hmImproveMRPageByDept").permitAll()
-                .antMatchers("/print/export/improveMRExportByDept").permitAll()
-                .antMatchers("/consoleByDept/reHos31DaysPageByDept").permitAll()
-                .antMatchers("/print/export/reHos31DaysPageExportByDept").permitAll()
-                .antMatchers("/consoleByDept/unModifyMRSByDept").permitAll()
-                .antMatchers("/print/export/unModifyMRSExportByDept").permitAll()
-                .antMatchers("/consoleByDept/unModifyMRPageByDept").permitAll()
-                .antMatchers("/print/export/unModifyMRPageExportByDept").permitAll()
-                .antMatchers("/consoleByDept/medicalCheckFormKs").permitAll()
-                .antMatchers("/print/export/medicalCheckExportByDept").permitAll()
-                .antMatchers("/consoleByDept/medicalCheckTitleKs").permitAll()
-                .antMatchers("/qc/medCheckInfo/createMedBeHospitalInfoType").permitAll()
-                .antMatchers("/**").authenticated();
-        //                .antMatchers("/**").permitAll();
-    }
-    @Override
-    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
-        log.info("Configuring ResourceServerSecurityConfigurer");
-        resources.resourceId("user-service").tokenStore(new JwtTokenStore(jwtTokenEnhancerClient()));
-    }
-    @Autowired
-    private CustomAccessTokenConverter customAccessTokenConverter;
-
-    @Bean("jwtTokenEnhancerClient")
-    protected JwtAccessTokenConverter jwtTokenEnhancerClient() {
-        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
-        Resource resource = new ClassPathResource("public.cert");
-        String publicKey;
-        try {
-            publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
-        } catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-        converter.setVerifierKey(publicKey);
-        //不设置这个会出现 Cannot convert access token to JSON
-        converter.setVerifier(new RsaVerifier(publicKey));
-        converter.setAccessTokenConverter(customAccessTokenConverter);
-        log.info("Created jwtTokenEnhancerClient success");
-        return converter;
-    }
-}

+ 0 - 69
security-center/src/main/java/com/lantone/security/config/WebSecurityConfigurer.java

@@ -1,69 +0,0 @@
-package com.lantone.security.config;
-
-import com.lantone.security.service.UrlUserService;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
-import org.springframework.security.config.annotation.web.builders.HttpSecurity;
-import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.crypto.factory.PasswordEncoderFactories;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.security.web.AuthenticationEntryPoint;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- * @Description: WebSecurity配置类
- * @author: gaodm
- * @time: 2018/8/2 14:24
- */
-@Configuration
-class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
-
-    @Override
-    @Bean
-    public AuthenticationManager authenticationManagerBean() throws Exception {
-        return super.authenticationManagerBean();
-    }
-
-    @Override
-    protected void configure(HttpSecurity http) throws Exception {
-        //CSRF:因为不再依赖于Cookie,所以你就不需要考虑对CSRF(跨站请求伪造)的防范。
-        http
-                .csrf().disable()
-                .exceptionHandling()
-                // .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
-                .authenticationEntryPoint(new AuthenticationEntryPoint() {
-                    @Override
-                    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
-                        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
-                    }
-                })
-                .and()
-                .authorizeRequests()
-                .regexMatchers("/actuator.*").permitAll()
-                .antMatchers("/**").authenticated()
-                .and()
-                .httpBasic();
-    }
-
-    @Bean
-    UrlUserService urlUserService() {
-        return new UrlUserService();
-    }
-
-    @Bean
-    public PasswordEncoder passwordEncoder() {
-        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
-    }
-
-    @Override
-    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
-        auth.userDetailsService(urlUserService()).passwordEncoder(passwordEncoder());
-    }
-}

+ 0 - 75
security-center/src/main/java/com/lantone/security/dto/JWT.java

@@ -1,75 +0,0 @@
-package com.lantone.security.dto;
-
-/**
- * @Description: JWT实体类
- * @author: gaodm
- * @time: 2018/8/2 13:53
- */
-public class JWT {
-    private String access_token;
-    private String token_type;
-    private String refresh_token;
-    private int expires_in;
-    private String scope;
-    private String jti;
-
-    public String getAccess_token() {
-        return access_token;
-    }
-
-    public void setAccess_token(String access_token) {
-        this.access_token = access_token;
-    }
-
-    public String getToken_type() {
-        return token_type;
-    }
-
-    public void setToken_type(String token_type) {
-        this.token_type = token_type;
-    }
-
-    public String getRefresh_token() {
-        return refresh_token;
-    }
-
-    public void setRefresh_token(String refresh_token) {
-        this.refresh_token = refresh_token;
-    }
-
-    public int getExpires_in() {
-        return expires_in;
-    }
-
-    public void setExpires_in(int expires_in) {
-        this.expires_in = expires_in;
-    }
-
-    public String getScope() {
-        return scope;
-    }
-
-    public void setScope(String scope) {
-        this.scope = scope;
-    }
-
-    public String getJti() {
-        return jti;
-    }
-
-    public void setJti(String jti) {
-        this.jti = jti;
-    }
-
-    @Override
-    public String toString() {
-        return "JWT{" +
-                "access_token='" + access_token + '\'' +
-                ", token_type='" + token_type + '\'' +
-                ", refresh_token='" + refresh_token + '\'' +
-                ", expires_in=" + expires_in +
-                ", scope='" + scope + '\'' +
-                ", jti='" + jti + '\'' +
-                '}';
-    }
-}

+ 0 - 27
security-center/src/main/java/com/lantone/security/dto/JwtDTO.java

@@ -1,27 +0,0 @@
-package com.lantone.security.dto;
-
-import com.lantone.dblayermbg.entity.Organize;
-import com.lantone.dblayermbg.entity.Role;
-import lombok.Getter;
-import lombok.Setter;
-
-import java.util.List;
-
-
-/**
- * @Description: jwt 输出类
- * @author: gaodm
- * @time: 2018/8/2 14:22
- */
-@Getter
-@Setter
-public class JwtDTO {
-    private String accessToken;
-    private String refreshToken;
-    private Integer type; //用户类型
-    private String typeCn; //用户类型中文
-    //用户组织列表
-    private List<OrganizeDTO> organizes;
-    //用户密码复杂度是否符合
-//    private String passwordComplexity;
-}

+ 0 - 16
security-center/src/main/java/com/lantone/security/dto/JwtStore.java

@@ -1,16 +0,0 @@
-package com.lantone.security.dto;
-
-import lombok.Getter;
-import lombok.Setter;
-
-/**
- * @Description:
- * @author: gaodm
- * @time: 2018/10/29 14:38
- */
-@Getter
-@Setter
-public class JwtStore {
-    private String accessToken;
-    private String refreshToken;
-}

+ 0 - 131
security-center/src/main/java/com/lantone/security/entity/SysUserUaa.java

@@ -1,131 +0,0 @@
-package com.lantone.security.entity;
-
-import com.baomidou.mybatisplus.annotation.IdType;
-import com.baomidou.mybatisplus.annotation.TableId;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import lombok.Data;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-/**
- * <p>
- * 系统用户表
- * </p>
- *
- * @author gaodm
- * @since 2018-08-30
- */
-@Data
-public class SysUserUaa implements UserDetails, Serializable {
-
-    private static final long serialVersionUID = 1L;
-
-    /**
-     * 用户ID
-     */
-    @TableId(value = "id", type = IdType.AUTO)
-    private Long id;
-
-    /**
-     * 是否删除,N:未删除,Y:删除
-     */
-    private String isDeleted;
-
-    /**
-     * 记录创建时间
-     */
-    private Date gmtCreate;
-
-    /**
-     * 记录修改时间,如果时间是1970年则表示纪录未修改
-     */
-    private Date gmtModified;
-
-    /**
-     * 创建人,0表示无创建人值
-     */
-    private String creator;
-
-    /**
-     * 修改人,如果为0则表示纪录未修改
-     */
-    private String modifier;
-
-    /**
-     * 用户密码
-     */
-    private String password;
-
-    /**
-     * 用户名
-     */
-    private String username;
-
-    /**
-     * 1内部用户,0外部用户(默认0)
-     */
-    private Integer type;
-
-    /**
-     * 医院ID
-     */
-    private Long hospitalId;
-
-    private List<? extends GrantedAuthority> authorities;
-    private Map<String,List> functionAuthorities;
-
-    @Override
-    @JsonIgnore
-    public boolean isAccountNonExpired() {
-        return true;
-    }
-
-    @Override
-    @JsonIgnore
-    public boolean isAccountNonLocked() {
-        return true;
-    }
-
-    @Override
-    @JsonIgnore
-    public boolean isCredentialsNonExpired() {
-        return true;
-    }
-
-    @Override
-    @JsonIgnore
-    public boolean isEnabled() {
-        return true;
-    }
-
-    @JsonIgnore
-    public Collection<? extends GrantedAuthority> getAuthorities() {
-        return authorities;
-    }
-
-    public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) {
-        this.authorities = authorities;
-    }
-
-
-
-    @Override
-    public String toString() {
-        return "User{" +
-                "id=" + id +
-                ", isDeleted=" + isDeleted +
-                ", gmtCreate=" + gmtCreate +
-                ", gmtModified=" + gmtModified +
-                ", creator=" + creator +
-                ", modifier=" + modifier +
-                ", password=" + password +
-                ", username=" + username +
-                "}";
-    }
-}

+ 0 - 21
security-center/src/main/java/com/lantone/security/entity/Token.java

@@ -1,21 +0,0 @@
-package com.lantone.security.entity;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import java.io.Serializable;
-
-/**
- * @Description: token
- * @Author: ztg
- * @Date: 2018/9/19 13:14
- */
-@Getter
-@Setter
-public class Token implements Serializable {
-
-    private static final long serialVersionUID = 1L;
-
-    private String token;
-
-}

+ 0 - 83
security-center/src/main/java/com/lantone/security/exception/CommonExceptionHandler.java

@@ -1,83 +0,0 @@
-package com.lantone.security.exception;
-
-import com.diagbot.dto.RespDTO;
-import com.diagbot.exception.CommonErrorCode;
-import com.diagbot.exception.CommonException;
-import com.diagbot.util.GsonUtil;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.ResponseEntity;
-import org.springframework.validation.BindException;
-import org.springframework.validation.FieldError;
-import org.springframework.web.bind.MethodArgumentNotValidException;
-import org.springframework.web.bind.MissingServletRequestParameterException;
-import org.springframework.web.bind.annotation.ControllerAdvice;
-import org.springframework.web.bind.annotation.ExceptionHandler;
-import org.springframework.web.bind.annotation.ResponseBody;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- * @Description: 错误通用处理
- * @author: gaodm
- * @time: 2018/8/2 14:22
- */
-@ControllerAdvice
-@ResponseBody
-@Slf4j
-public class CommonExceptionHandler {
-
-    @ExceptionHandler(Exception.class)
-    public ResponseEntity<RespDTO> handleException(Exception e) {
-        RespDTO resp = new RespDTO();
-        if (e instanceof BindException) {
-            BindException ex = (BindException) e;
-            Map<String, String> stringMap = new HashMap<>();
-            for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
-                stringMap.put(fieldError.getField(), fieldError.getDefaultMessage());
-            }
-            String msg = GsonUtil.toJson(stringMap);
-            log.warn("【参数异常】:{}", msg);
-            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
-            resp.msg = msg;
-            return new ResponseEntity(resp, HttpStatus.OK);
-        }
-        if (e instanceof MethodArgumentNotValidException) {
-            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
-            Map<String, String> stringMap = new HashMap<>();
-            for (FieldError fieldError : ex.getBindingResult().getFieldErrors()) {
-                stringMap.put(fieldError.getField(), fieldError.getDefaultMessage());
-            }
-            String msg = GsonUtil.toJson(stringMap);
-            log.warn("【参数异常】:{}", msg);
-            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
-            resp.msg = msg;
-            return new ResponseEntity(resp, HttpStatus.OK);
-        }
-        if (e instanceof MissingServletRequestParameterException) {
-            MissingServletRequestParameterException ex = (MissingServletRequestParameterException) e;
-            Map<String, String> stringMap = new HashMap<>();
-            stringMap.put(ex.getParameterName(), "不能为null");
-            String msg = GsonUtil.toJson(stringMap);
-            log.warn("【参数异常】:{}", msg);
-            resp.code = CommonErrorCode.PARAM_ERROR.getCode();
-            resp.msg = msg;
-            return new ResponseEntity(resp, HttpStatus.OK);
-        }
-        if (e instanceof CommonException) {
-            CommonException taiChiException = (CommonException) e;
-            resp.code = taiChiException.getCode();
-            resp.msg = e.getMessage();
-            log.error("【业务异常】:{}", e.getMessage());
-            return new ResponseEntity(resp, HttpStatus.OK);
-        }
-        resp.code = CommonErrorCode.FAIL.getCode();
-        resp.msg = e.getMessage();
-        log.error("【系统异常】:{}", e.getMessage());
-        e.printStackTrace();
-        return new ResponseEntity(resp, HttpStatus.OK);
-    }
-
-}

+ 0 - 51
security-center/src/main/java/com/lantone/security/exception/ServiceErrorCode.java

@@ -1,51 +0,0 @@
-package com.lantone.security.exception;
-
-import com.diagbot.exception.ErrorCode;
-
-/**
- * @Description: 本服务错误码
- * 系统码(3位) + 等级码(1位) + 4位顺序号
- * 系统码 通用码 000;用户中心 100; 管理中心 200;
- * @author: gaodm
- * @time: 2018/9/10 11:11
- */
-public enum ServiceErrorCode implements ErrorCode {
-    USER_NOT_FOUND("10020000", "该账号暂未注册或已被禁用,请联系管理员"),
-    USER_PASSWORD_ERROR("10020001", "账号或密码不正确"),
-    GET_TOKEN_FAIL("10020002", "获取token失败"),
-    TOKEN_IS_NOT_MATCH_USER("10020003", "请使用自己的token进行接口请求"),
-
-    SMS_SEND_ERROR("10020004", "短信发送错误"),
-    USER_BIND_ERROR("10020005", "用户手机号已经绑定无需再次验证"),
-    USER_UN_BIND_ERROR("10020006", "用户手机号未绑定无需解绑"),
-    VERIFYCODE_ERROR("10020007", "图片验证码生成错误"),
-    USER_EXIST("10020008", "该账号已注册"),
-    EMAIL_IS_NULL("10020009", "请输入邮箱");
-
-    private String code;
-    private String msg;
-
-
-    ServiceErrorCode(String code, String msg) {
-        this.code = code;
-        this.msg = msg;
-    }
-
-
-    public String getCode() {
-        return code;
-    }
-
-    public String getMsg() {
-        return msg;
-    }
-
-    public static ServiceErrorCode codeOf(String code) {
-        for (ServiceErrorCode state : values()) {
-            if (state.getCode() == code) {
-                return state;
-            }
-        }
-        return null;
-    }
-}

+ 0 - 13
security-center/src/main/java/com/lantone/security/facade/TokenFacade.java

@@ -1,13 +0,0 @@
-package com.lantone.security.facade;
-
-import com.lantone.security.service.impl.SysTokenServiceImpl;
-import org.springframework.stereotype.Component;
-
-/**
- * @Description: token实现
- * @author: gaodm
- * @time: 2018/10/29 14:24
- */
-@Component
-public class TokenFacade extends SysTokenServiceImpl {
-}

+ 35 - 0
security-center/src/main/java/com/lantone/security/facade/UserAdminFacade.java

@@ -0,0 +1,35 @@
+package com.lantone.security.facade;
+
+import com.lantone.common.api.CommonResult;
+import com.lantone.common.constant.AuthConstant;
+import com.lantone.security.service.AuthService;
+import com.lantone.security.vo.LoginVO;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Description: 用户管理-业务处理类
+ * @author: rengb
+ * @time: 2021/7/20 12:39
+ */
+@Component
+public class UserAdminFacade {
+
+    @Autowired
+    private AuthService authService;
+
+    public CommonResult login(LoginVO loginVO) {
+        Map<String, String> params = new HashMap<>();
+        params.put("client_id", AuthConstant.USER_ADMIN_CLIENT_ID);
+        params.put("client_secret", "123456");
+        params.put("grant_type", "password");
+        params.put("username", loginVO.getUsername());
+        params.put("password", loginVO.getPassword());
+        CommonResult restResult = authService.getAccessToken(params);
+        return restResult;
+    }
+
+}

+ 135 - 141
security-center/src/main/java/com/lantone/security/facade/UserLoginFacade.java

@@ -1,141 +1,135 @@
-package com.lantone.security.facade;
-
-import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.diagbot.enums.IsDeleteEnum;
-import com.diagbot.exception.CommonErrorCode;
-import com.diagbot.exception.CommonException;
-import com.diagbot.util.BeanUtil;
-import com.diagbot.util.EntityUtil;
-import com.diagbot.util.ListUtil;
-import com.diagbot.util.StringUtil;
-import com.lantone.dblayermbg.entity.Organize;
-import com.lantone.dblayermbg.entity.Role;
-import com.lantone.dblayermbg.entity.User;
-import com.lantone.dblayermbg.entity.UserRole;
-import com.lantone.dblayermbg.facade.UserRoleFacade;
-import com.lantone.dblayermbg.service.impl.UserServiceImpl;
-import com.lantone.security.client.AuthServiceClient;
-import com.lantone.security.dto.JWT;
-import com.lantone.security.dto.JwtDTO;
-import com.lantone.security.dto.JwtStore;
-import com.lantone.security.dto.MenuInfoDTO;
-import com.lantone.security.dto.OrganizeDTO;
-import com.lantone.security.enums.StatusEnum;
-import com.lantone.security.exception.ServiceErrorCode;
-import com.lantone.security.util.SysUserUtils;
-import org.springframework.beans.BeanUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.crypto.factory.PasswordEncoderFactories;
-import org.springframework.security.crypto.password.PasswordEncoder;
-import org.springframework.stereotype.Component;
-import org.springframework.util.DigestUtils;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * <p>
- * 系统用户表 服务实现类Facade
- * </p>
- */
-@Component
-public class UserLoginFacade extends UserServiceImpl {
-    @Autowired
-    private TokenFacade tokenFacade;
-    @Autowired
-    private AuthServiceClient authServiceClient;
-    @Autowired
-    private UserRoleFacade userRoleFacade;
-
-
-    /**
-     * 获取jwt
-     *
-     * @param username 用户名
-     * @param password 密码
-     * @return jwt
-     */
-    public JwtDTO getJwt(String username, String password) {
-        JwtDTO data = new JwtDTO();
-        if (StringUtil.isBlank(username)) {
-            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
-                    "请输入用户名");
-        }
-        if (StringUtil.isBlank(password)) {
-            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
-                    "请输入密码");
-        }
-        //使用MD5对密码进行加密
-        String MD5Password = DigestUtils.md5DigestAsHex(password.getBytes());
-        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
-        userQueryWrapper.eq("username", username)
-                .eq("status", StatusEnum.Enable.getKey())
-                .eq("is_deleted", IsDeleteEnum.N.getKey());
-        User user = this.getOne(userQueryWrapper, false);
-        if (null == user) {
-            throw new CommonException(ServiceErrorCode.USER_NOT_FOUND);
-        }
-        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
-        if (!passwordEncoder.matches(MD5Password, user.getPassword())) {
-            throw new CommonException(ServiceErrorCode.USER_PASSWORD_ERROR);
-        }
-        JWT jwt = authServiceClient.getToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2",
-                "password", username, MD5Password);
-        if (null == jwt) {
-            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
-        }
-        data.setAccessToken(jwt.getAccess_token());
-        data.setRefreshToken(jwt.getRefresh_token());
-        //获取用户组织信息
-        Long id = user.getId();
-        List<Organize> organizes = this.baseMapper.getUserOrganizeByUserID(id);
-        if (organizes != null && !organizes.isEmpty()) {
-            List<OrganizeDTO> organizeDTOS = new ArrayList<>();
-            //获取用户当前组织下的角色信息
-            for (Organize organize : organizes) {
-                OrganizeDTO organizeDTO = new OrganizeDTO();
-                BeanUtils.copyProperties(organize,organizeDTO);
-                if(StringUtil.isNotBlank(organize.getOrganizeId())){
-                    List<Role> roles= this.baseMapper.getUserRoleByUserID(id,organize.getOrganizeId());
-                    organizeDTO.setRoles(roles);
-                }
-                organizeDTOS.add(organizeDTO);
-            }
-            data.setOrganizes(organizeDTOS);
-        }
-
-        //token存入redis
-        JwtStore jwtStore = new JwtStore();
-        jwtStore.setAccessToken(jwt.getAccess_token());
-        jwtStore.setRefreshToken(jwt.getRefresh_token());
-        tokenFacade.createToken(jwtStore);
-        return data;
-    }
-    /**
-     * @Author songxl
-     * @Description 获取用户显示的菜单
-     * @Date  2021/7/19
-     * @Param []
-     * @Return com.lantone.security.dto.MenuInfoDTO
-     * @MethodName getUserOrgMenu
-     */
-    public MenuInfoDTO getUserOrgMenu() {
-        MenuInfoDTO menuInfoDTO = new MenuInfoDTO();
-        Set<String> roleSet = new HashSet<>();
-        Long userId = Long.parseLong(SysUserUtils.getCurrentPrincipleID());
-        //获取当前登录用户角色
-        List<UserRole> userRoles = userRoleFacade.list(new QueryWrapper<UserRole>()
-                .eq("is_deleted", IsDeleteEnum.N.getKey())
-                .eq("status", StatusEnum.Enable.getKey())
-                .eq("id", userId));
-        //1.超级管理员
-        if(!ListUtil.isEmpty(userRoles)&&userRoles.contains(0)){
-
-        }
-        //添加菜单信息
-        return menuInfoDTO;
-    }
-
-}
+//package com.lantone.security.facade;
+//
+//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+//import com.diagbot.enums.IsDeleteEnum;
+//import com.diagbot.exception.CommonErrorCode;
+//import com.diagbot.exception.CommonException;
+//import com.diagbot.util.ListUtil;
+//import com.diagbot.util.StringUtil;
+//import com.lantone.dblayermbg.entity.Organize;
+//import com.lantone.dblayermbg.entity.Role;
+//import com.lantone.dblayermbg.entity.User;
+//import com.lantone.dblayermbg.entity.UserRole;
+//import com.lantone.dblayermbg.facade.UserRoleFacade;
+//import com.lantone.dblayermbg.service.impl.UserServiceImpl;
+//import com.lantone.security.client.AuthServiceClient;
+//import com.lantone.security.dto.MenuInfoDTO;
+//import com.lantone.security.dto.OrganizeDTO;
+//import com.lantone.security.enums.StatusEnum;
+//import com.lantone.security.util.SysUserUtils;
+//import org.springframework.beans.BeanUtils;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.security.crypto.factory.PasswordEncoderFactories;
+//import org.springframework.security.crypto.password.PasswordEncoder;
+//import org.springframework.stereotype.Component;
+//import org.springframework.util.DigestUtils;
+//
+//import java.util.ArrayList;
+//import java.util.HashSet;
+//import java.util.List;
+//import java.util.Set;
+//
+///**
+// * <p>
+// * 系统用户表 服务实现类Facade
+// * </p>
+// */
+//@Component
+//public class UserLoginFacade extends UserServiceImpl {
+//    @Autowired
+//    private TokenFacade tokenFacade;
+//    @Autowired
+//    private AuthServiceClient authServiceClient;
+//    @Autowired
+//    private UserRoleFacade userRoleFacade;
+//
+//
+//    /**
+//     * 获取jwt
+//     *
+//     * @param username 用户名
+//     * @param password 密码
+//     * @return jwt
+//     */
+//    public JwtDTO getJwt(String username, String password) {
+//        JwtDTO data = new JwtDTO();
+//        if (StringUtil.isBlank(username)) {
+//            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
+//                    "请输入用户名");
+//        }
+//        if (StringUtil.isBlank(password)) {
+//            throw new CommonException(CommonErrorCode.PARAM_IS_NULL,
+//                    "请输入密码");
+//        }
+//        //使用MD5对密码进行加密
+//        String MD5Password = DigestUtils.md5DigestAsHex(password.getBytes());
+//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
+//        userQueryWrapper.eq("username", username)
+//                .eq("status", StatusEnum.Enable.getKey())
+//                .eq("is_deleted", IsDeleteEnum.N.getKey());
+//        User user = this.getOne(userQueryWrapper, false);
+//        if (null == user) {
+//            throw new CommonException(ServiceErrorCode.USER_NOT_FOUND);
+//        }
+//        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
+//        if (!passwordEncoder.matches(MD5Password, user.getPassword())) {
+//            throw new CommonException(ServiceErrorCode.USER_PASSWORD_ERROR);
+//        }
+//        JWT jwt = authServiceClient.getToken("Basic dWFhLXNlcnZpY2U6MTIzNDU2",
+//                "password", username, MD5Password);
+//        if (null == jwt) {
+//            throw new CommonException(ServiceErrorCode.GET_TOKEN_FAIL);
+//        }
+//        data.setAccessToken(jwt.getAccess_token());
+//        data.setRefreshToken(jwt.getRefresh_token());
+//        //获取用户组织信息
+//        Long id = user.getId();
+//        List<Organize> organizes = this.baseMapper.getUserOrganizeByUserID(id);
+//        if (organizes != null && !organizes.isEmpty()) {
+//            List<OrganizeDTO> organizeDTOS = new ArrayList<>();
+//            //获取用户当前组织下的角色信息
+//            for (Organize organize : organizes) {
+//                OrganizeDTO organizeDTO = new OrganizeDTO();
+//                BeanUtils.copyProperties(organize,organizeDTO);
+//                if(StringUtil.isNotBlank(organize.getOrganizeId())){
+//                    List<Role> roles= this.baseMapper.getUserRoleByUserID(id,organize.getOrganizeId());
+//                    organizeDTO.setRoles(roles);
+//                }
+//                organizeDTOS.add(organizeDTO);
+//            }
+//            data.setOrganizes(organizeDTOS);
+//        }
+//
+//        //token存入redis
+//        JwtStore jwtStore = new JwtStore();
+//        jwtStore.setAccessToken(jwt.getAccess_token());
+//        jwtStore.setRefreshToken(jwt.getRefresh_token());
+//        tokenFacade.createToken(jwtStore);
+//        return data;
+//    }
+//    /**
+//     * @Author songxl
+//     * @Description 获取用户显示的菜单
+//     * @Date  2021/7/19
+//     * @Param []
+//     * @Return com.lantone.security.dto.MenuInfoDTO
+//     * @MethodName getUserOrgMenu
+//     */
+//    public MenuInfoDTO getUserOrgMenu() {
+//        MenuInfoDTO menuInfoDTO = new MenuInfoDTO();
+//        Set<String> roleSet = new HashSet<>();
+//        Long userId = Long.parseLong(SysUserUtils.getCurrentPrincipleID());
+//        //获取当前登录用户角色
+//        List<UserRole> userRoles = userRoleFacade.list(new QueryWrapper<UserRole>()
+//                .eq("is_deleted", IsDeleteEnum.N.getKey())
+//                .eq("status", StatusEnum.Enable.getKey())
+//                .eq("id", userId));
+//        //1.超级管理员
+//        if(!ListUtil.isEmpty(userRoles)&&userRoles.contains(0)){
+//
+//        }
+//        //添加菜单信息
+//        return menuInfoDTO;
+//    }
+//
+//}

+ 21 - 0
security-center/src/main/java/com/lantone/security/service/AuthService.java

@@ -0,0 +1,21 @@
+package com.lantone.security.service;
+
+import com.lantone.common.api.CommonResult;
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+
+import java.util.Map;
+
+/**
+ * @Description: 认证服务远程调用
+ * @author: rengb
+ * @time: 2021/1/5 18:27
+ */
+@FeignClient("user-auth")
+public interface AuthService {
+
+    @PostMapping(value = "/oauth/token")
+    CommonResult getAccessToken(@RequestParam Map<String, String> parameters);
+
+}

+ 0 - 55
security-center/src/main/java/com/lantone/security/service/SysTokenService.java

@@ -1,55 +0,0 @@
-package com.lantone.security.service;
-
-
-import com.lantone.security.dto.JwtStore;
-
-import java.util.List;
-
-/**
- * @Description: Token验证类
- * @author: gaodm
- * @time: 2018/10/29 13:35
- */
-public interface SysTokenService {
-
-    /**
-     * 创建token
-     *
-     * @param token 用户token
-     * @return
-     */
-    Boolean createToken(JwtStore token);
-
-    /**
-     * 验证token是否有效
-     *
-     * @param token 待验证的token
-     * @param type  1:accessToken,2:refreshToken
-     * @return
-     */
-    Boolean verifyToken(String token, Integer type);
-
-    /**
-     * 删除用户token
-     *
-     * @param userId 用户ID
-     * @return 删除是否成功
-     */
-    Boolean deleteToken(String userId);
-
-    /**
-     * 批量删除用户token
-     *
-     * @param userIds 用户列表
-     * @return 删除是否成功
-     */
-    Boolean deleteBatchToken(List<Long> userIds);
-
-    /**
-     * 获取用户jwt
-     *
-     * @param userId 用户ID
-     * @return jwt信息
-     */
-    JwtStore getToken(String userId);
-}

+ 0 - 40
security-center/src/main/java/com/lantone/security/service/UrlGrantedAuthority.java

@@ -1,40 +0,0 @@
-package com.lantone.security.service;
-
-import org.springframework.security.core.GrantedAuthority;
-
-/**
- * @Description: 自定义权限信息
- * @author: gaodm
- * @time: 2018/8/23 14:09
- */
-public class UrlGrantedAuthority implements GrantedAuthority {
-
-    private String permissionUrl;
-    private String method;
-
-    public String getPermissionUrl() {
-        return permissionUrl;
-    }
-
-    public void setPermissionUrl(String permissionUrl) {
-        this.permissionUrl = permissionUrl;
-    }
-
-    public String getMethod() {
-        return method;
-    }
-
-    public void setMethod(String method) {
-        this.method = method;
-    }
-
-    public UrlGrantedAuthority(String permissionUrl, String method) {
-        this.permissionUrl = permissionUrl;
-        this.method = method;
-    }
-
-    @Override
-    public String getAuthority() {
-        return this.permissionUrl + ";" + this.method;
-    }
-}

+ 0 - 64
security-center/src/main/java/com/lantone/security/service/UrlUserService.java

@@ -1,64 +0,0 @@
-package com.lantone.security.service;
-
-import com.lantone.security.entity.SysUserUaa;
-import com.lantone.security.enums.ConstantEnum;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.userdetails.UserDetails;
-import org.springframework.security.core.userdetails.UserDetailsService;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-import org.springframework.stereotype.Service;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @Description: 用户权限信息获取
- * @author: gaodm
- * @time: 2018/8/23 11:39
- */
-@Service
-public class UrlUserService implements UserDetailsService {
-
-    @Override
-    public UserDetails loadUserByUsername(String userName) { //重写loadUserByUsername 方法获得 userdetails 类型用户
-        //1.获取用户信息
-//        SysUserUaa user = userUaaMapper.getByUserName(userName);
-        SysUserUaa user = null;
-        if (user != null) {
-            //2.获取用户功能权限
-//            List<SysPermission> permissions = permissionMapper.getByUserId(user.getId());
-            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
-//            for (SysPermission permission : permissions) {
-//                if (null != permission && StringUtils.isNotBlank(permission.getPermissionUrl())) {
-//                    GrantedAuthority grantedAuthority
-//                            = new UrlGrantedAuthority(permission.getPermissionUrl(), permission.getMethod());
-//                    grantedAuthorities.add(grantedAuthority);
-//                }
-//            }
-            //2.1将库中的功能权限赋给用户
-            user.setGrantedAuthorities(grantedAuthorities);
-//            if (user.getType().equals(ConstantEnum.OUTER_USER.getKey())) {
-                //2.2获取用户医院信息
-//                SysUserUaa userHosp = userUaaMapper.getHospByUserName(userName);
-//                if (null == userHosp) {
-//                    throw new UsernameNotFoundException("医院管理人员: " + userName + " 未绑定医院");
-//                } else {
-//                    user.setHospitalId(userHosp.getHospitalId());
-//                }
-//            } else {
-//                user.setHospitalId(-1L);
-//            }
-
-
-            //3.获取当前登录用户的功能权限
-
-            //3.1获取用户可查看的doctor、dept
-
-            //3.2将功能权限赋予用户
-            user.setFunctionAuthorities(null);
-            return user;
-        } else {
-            throw new UsernameNotFoundException("admin: " + userName + " do not exist");
-        }
-    }
-}

+ 0 - 196
security-center/src/main/java/com/lantone/security/service/impl/SysTokenServiceImpl.java

@@ -1,196 +0,0 @@
-package com.lantone.security.service.impl;
-
-import com.auth0.jwt.interfaces.Claim;
-import com.auth0.jwt.interfaces.DecodedJWT;
-import com.diagbot.util.DateUtil;
-import com.diagbot.util.JwtUtil;
-import com.lantone.security.dto.JwtStore;
-import com.lantone.security.service.SysTokenService;
-import lombok.extern.slf4j.Slf4j;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.dao.DataAccessException;
-import org.springframework.data.redis.connection.RedisConnection;
-import org.springframework.data.redis.core.RedisCallback;
-import org.springframework.data.redis.core.RedisTemplate;
-import org.springframework.stereotype.Service;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @Description: Token验证类 实现
- * @author: gaodm
- * @time: 2018/10/29 13:34
- */
-@Slf4j
-@Service
-public class SysTokenServiceImpl implements SysTokenService {
-
-    @Autowired
-    @Qualifier("redisTemplateForToken")
-    RedisTemplate redisForToken;
-
-    private byte[] serializeKey(Object o) {
-        return redisForToken.getKeySerializer().serialize(o);
-    }
-
-    private byte[] serializeValue(Object o) {
-        return redisForToken.getValueSerializer().serialize(o);
-    }
-
-    private Object deserializeValue(byte[] b) {
-        return redisForToken.getValueSerializer().deserialize(b);
-    }
-
-    private byte[] getUserTokenKey(String userId) {
-        String userTokensFormat = "user_tokens_%s";
-        return serializeKey(String.format(userTokensFormat, userId));
-    }
-
-    /**
-     * 创建token
-     *
-     * @param token 用户token
-     * @return
-     */
-    @Override
-    public Boolean createToken(JwtStore token) {
-        DecodedJWT jwt = JwtUtil.decodedJWT(token.getRefreshToken());
-        Map<String, Claim> claims = jwt.getClaims();
-        String userId = claims.get("user_id").asInt().toString();
-        Date expDate = claims.get("exp").asDate();
-        final byte[] redis_key = getUserTokenKey(userId);
-        redisForToken.execute(new RedisCallback<Object>() {
-            @Override
-            public Object doInRedis(RedisConnection connection) throws DataAccessException {
-                //获取旧的
-                byte[] bytes = connection.get(redis_key);
-                //删除旧的
-                if (bytes != null) {
-                    connection.del(bytes);
-                }
-                //设置新的
-                connection.setEx(
-                        redis_key,
-                        (expDate.getTime() - DateUtil.now().getTime()) / 1000,
-                        serializeValue(token)
-                );
-                return true;
-            }
-        });
-        return true;
-    }
-
-    /**
-     * 验证token是否有效
-     *
-     * @param token 待验证的token
-     * @param type  1:accessToken,2:refreshToken
-     * @return
-     */
-    @Override
-    public Boolean verifyToken(String token, Integer type) {
-        Boolean res = false;
-        if (null == token) {
-            return false;
-        }
-        String userId = JwtUtil.getUserId(token);
-        //从redis中取出
-        final byte[] redis_key = getUserTokenKey(userId);
-        JwtStore tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
-            @Override
-            public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
-                byte[] bytes = connection.get(redis_key);
-                if (bytes == null) {
-                    return null;
-                }
-                return (JwtStore) deserializeValue(bytes);
-            }
-        });
-
-        if (null != tokenStore) {
-            if (type == 1) {
-                if (null != tokenStore.getAccessToken() && tokenStore.getAccessToken().equals(token)) {
-                    res = true;
-                }
-            }
-
-            if (type == 2) {
-                if (null != tokenStore.getRefreshToken() && tokenStore.getRefreshToken().equals(token)) {
-                    res = true;
-                }
-            }
-        }
-
-        return res;
-    }
-
-    /**
-     * 删除用户token
-     *
-     * @param userId 用户ID
-     * @return 删除是否成功
-     */
-    @Override
-    public Boolean deleteToken(String userId) {
-        final byte[] redis_key = getUserTokenKey(userId);
-        Long l = (Long) redisForToken.execute(new RedisCallback<Long>() {
-            @Override
-            public Long doInRedis(RedisConnection connection) throws DataAccessException {
-                return connection.del(redis_key);
-            }
-        });
-        return l > 0;
-    }
-
-    /**
-     * 批量删除用户token
-     *
-     * @param userIds 用户列表
-     * @return 删除是否成功
-     */
-    @Override
-    public Boolean deleteBatchToken(List<Long> userIds) {
-        Long l = (Long) redisForToken.execute(new RedisCallback<Long>() {
-            @Override
-            public Long doInRedis(RedisConnection connection) throws DataAccessException {
-                connection.openPipeline();
-                Long cnt = 0L;
-                for (Long userId : userIds) {
-                    byte[] redis_key = getUserTokenKey(userId.toString());
-                    connection.del(redis_key);
-                    cnt++;
-                }
-                connection.closePipeline();
-                return cnt;
-            }
-        });
-        return l > 0;
-    }
-
-    /**
-     * 获取用户jwt
-     *
-     * @param userId 用户ID
-     * @return jwt信息
-     */
-    @Override
-    public JwtStore getToken(String userId) {
-        JwtStore tokenStore = null;
-        //从redis中取出
-        final byte[] redis_key = getUserTokenKey(userId);
-        tokenStore = (JwtStore) redisForToken.execute(new RedisCallback<JwtStore>() {
-            @Override
-            public JwtStore doInRedis(RedisConnection connection) throws DataAccessException {
-                byte[] bytes = connection.get(redis_key);
-                if (bytes == null) {
-                    return null;
-                }
-                return (JwtStore) deserializeValue(bytes);
-            }
-        });
-        return tokenStore;
-    }
-}

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 85
security-center/src/main/java/com/lantone/security/util/SysJwtUtil.java


+ 0 - 106
security-center/src/main/java/com/lantone/security/util/SysUserUtils.java

@@ -1,106 +0,0 @@
-package com.lantone.security.util;
-
-import com.diagbot.util.HttpUtils;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
-
-import java.util.List;
-
-/**
- * @Description: 用户工具类
- * @author: gaodm
- * @time: 2018/8/3 17:46
- */
-public class SysUserUtils {
-
-    private static final String AUTHORIZATION = "authorization";
-
-    /**
-     * 获取当前请求的token
-     *
-     * @return
-     */
-    public static String getCurrentToken() {
-        return HttpUtils.getHeaders(HttpUtils.getHttpServletRequest()).get(AUTHORIZATION);
-    }
-
-    /**
-     * 获取当前请求的用户名称
-     *
-     * @return
-     */
-    public static String getCurrentPrinciple() {
-        return (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
-    }
-
-    /**
-     * 获取当前请求的用户ID
-     *
-     * @return
-     */
-    public static String getCurrentPrincipleID() {
-        OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
-        return SysJwtUtil.getUserId(oauthDetails.getTokenValue());
-    }
-
-    /**
-     * 获取当前请求用户的医院ID
-     *
-     * @return
-     */
-    public static String getCurrentHospitalID() {
-        OAuth2AuthenticationDetails oauthDetails = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
-        return SysJwtUtil.getHospId(oauthDetails.getTokenValue());
-    }
-
-
-    /**
-     * 判读当前token用户是否为接口所需的参数username
-     *
-     * @param username
-     * @return
-     */
-    public static boolean isMyself(String username) {
-        return username.equals(getCurrentPrinciple());
-    }
-
-    /**
-     * 获取当前请求Authentication
-     *
-     * @return
-     */
-    public static Authentication getCurrentAuthentication() {
-        return SecurityContextHolder.getContext().getAuthentication();
-    }
-
-    /**
-     * 获取当前请求的权限信息
-     *
-     * @return
-     */
-    public static List<SimpleGrantedAuthority> getCurrentAuthorities() {
-        return (List<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
-    }
-
-    /**
-     * @param role
-     * @return
-     */
-    public static boolean hasRole(String role) {
-        if (!role.startsWith("ROLE_")) {
-            role = "ROLE_" + role;
-        }
-        boolean hasRole = false;
-        List<SimpleGrantedAuthority> list = getCurrentAuthorities();
-        for (SimpleGrantedAuthority s : list) {
-            if (role.equals(s.getAuthority())) {
-                hasRole = true;
-                break;
-            }
-        }
-        return hasRole;
-    }
-
-}

+ 26 - 0
security-center/src/main/java/com/lantone/security/vo/LoginVO.java

@@ -0,0 +1,26 @@
+package com.lantone.security.vo;
+
+import io.swagger.annotations.ApiModelProperty;
+import lombok.Getter;
+import lombok.Setter;
+
+import javax.validation.constraints.NotEmpty;
+
+/**
+ * @Description: 用户登录参数
+ * @author: rengb
+ * @time: 2021/1/5 18:27
+ */
+@Getter
+@Setter
+public class LoginVO {
+
+    @NotEmpty
+    @ApiModelProperty(value = "用户名", required = true)
+    private String username;
+
+    @NotEmpty
+    @ApiModelProperty(value = "密码", required = true)
+    private String password;
+
+}

+ 0 - 18
security-center/src/main/java/com/lantone/security/vo/SysUserBaseVO.java

@@ -1,18 +0,0 @@
-package com.lantone.security.vo;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import javax.validation.constraints.NotNull;
-
-/**
- * @Description:
- * @author: gaodm
- * @time: 2020/4/28 9:23
- */
-@Getter
-@Setter
-public class SysUserBaseVO {
-    @NotNull(message = "请输入用户ID")
-    private Long userId;
-}

+ 0 - 20
security-center/src/main/java/com/lantone/security/vo/UserLoginNoPassVO.java

@@ -1,20 +0,0 @@
-package com.lantone.security.vo;
-
-import lombok.Getter;
-import lombok.Setter;
-
-import javax.validation.constraints.NotBlank;
-
-/**
- * @Description: 登录参数
- * @Author: ztg
- * @Date: 2018/9/28 13:14
- */
-@Getter
-@Setter
-public class UserLoginNoPassVO {
-
-    @NotBlank(message = "请输入用户名!")
-    private String username;
-
-}

+ 43 - 0
security-center/src/main/java/com/lantone/security/web/UserAdminController.java

@@ -0,0 +1,43 @@
+package com.lantone.security.web;
+
+import com.lantone.common.api.CommonResult;
+import com.lantone.security.facade.UserAdminFacade;
+import com.lantone.security.vo.LoginVO;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Controller;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.ResponseBody;
+
+/**
+ * @Description: 用户管理
+ * @author: rengb
+ * @time: 2021/1/5 18:27
+ */
+@Controller
+@Api(tags = "UserAdminController", description = "用户管理")
+@RequestMapping("/userAdmin")
+public class UserAdminController {
+
+    @Autowired
+    private UserAdminFacade userAdminFacade;
+
+    @ApiOperation(value = "登录以后返回token")
+    @RequestMapping(value = "/login", method = RequestMethod.POST)
+    @ResponseBody
+    public CommonResult login(@Validated @RequestBody LoginVO loginVO) {
+        return userAdminFacade.login(loginVO);
+    }
+
+    @ApiOperation(value = "登出功能")
+    @RequestMapping(value = "/logout", method = RequestMethod.POST)
+    @ResponseBody
+    public CommonResult logout() {
+        return CommonResult.success(null);
+    }
+
+}

+ 48 - 87
security-center/src/main/java/com/lantone/security/web/UserLoginController.java

@@ -1,87 +1,48 @@
-package com.lantone.security.web;
-
-import com.diagbot.annotation.SysLogger;
-import com.diagbot.dto.RespDTO;
-import com.lantone.security.dto.JwtDTO;
-import com.lantone.security.entity.Token;
-import com.lantone.security.facade.UserLoginFacade;
-import com.lantone.security.facade.TokenFacade;
-import com.lantone.security.vo.JwtVO;
-import com.lantone.security.vo.UserLoginNoPassVO;
-import com.lantone.security.vo.UserLoginVO;
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.oauth2.common.OAuth2AccessToken;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
-import springfox.documentation.annotations.ApiIgnore;
-
-
-/**
- * @Description: 用户账号API
- * @author: gaodm
- * @time: 2018/8/2 13:56
- */
-@RestController
-@Api(value = "用户账号API", tags = { "用户账号API" })
-@RequestMapping("/sys/user")
-@SuppressWarnings("unchecked")
-public class UserLoginController {
-
-    @Autowired
-    private TokenFacade tokenFacade;
-    @Autowired
-    private UserLoginFacade userFacade;
-
-    @ApiOperation(value = "验证token有效性[by:gaodm]",
-            notes = "token:token信息,必填<br>")
-    @PostMapping("/verifyToken")
-    @SysLogger("verifyToken")
-    @ApiIgnore
-    public RespDTO<Boolean> verifyToken(@RequestBody Token token) {
-        Boolean data = tokenFacade.verifyToken(token.getToken(), 1);
-        return RespDTO.onSuc(data);
-    }
-
-
-    @ApiOperation(value = "登录获取jwt[by:gaodm]",
-            notes = "username:用户名,必填<br>" +
-                    "password:密码, 必填, 默认密码:dc483e80a7a0bd9ef71d8cf973673924<br> ")
-    @PostMapping("/getJwt")
-    @SysLogger("getJwt")
-    public RespDTO<JwtDTO> getJwt(@RequestBody UserLoginVO userLoginVO) {
-        JwtDTO data = userFacade.getJwt(userLoginVO.getUsername(), userLoginVO.getPassword());
-        return RespDTO.onSuc(data);
-    }
-
-    @ApiOperation(value = "登录获取jwt[by:gaodm]",
-            notes = "username:用户名,必填<br>")
-    @PostMapping("/getJwtNoPass")
-    @SysLogger("getJwtNoPass")
-    public RespDTO<JwtDTO> getJwtNoPass(@RequestBody UserLoginNoPassVO userLoginNoPassVO) {
-//        JwtDTO data = userFacade.getJwtNoPass(userLoginNoPassVO.getUsername());
-        return RespDTO.onSuc(null);
-    }
-
-    @ApiOperation(value = "刷新jwt[by:gaodm]",
-            notes = "refreshToken:刷新令牌,必填<br>")
-    @PostMapping("/refreshJwt")
-    @SysLogger("refreshJwt")
-    public RespDTO<JwtDTO> refreshJwt(@RequestBody JwtVO jwtVO) {
-//        JwtDTO data = userFacade.refreshJwt(jwtVO.getToken());
-        return RespDTO.onSuc(null);
-    }
-
-    @ApiOperation(value = "验证Token[by:gaodm]",
-            notes = "checkToken:令牌,必填<br>")
-    @PostMapping("/checkToken")
-    @SysLogger("checkToken")
-    public RespDTO<OAuth2AccessToken> checkToken(@RequestBody JwtVO jwtVO) {
-//        OAuth2AccessToken data = userFacade.checkToken(jwtVO.getToken());
-        return RespDTO.onSuc(null);
-    }
-
-}
+//package com.lantone.security.web;
+//
+//import com.diagbot.annotation.SysLogger;
+//import com.diagbot.dto.RespDTO;
+//import com.lantone.security.facade.UserLoginFacade;
+//import com.lantone.security.vo.UserLoginVO;
+//import io.swagger.annotations.Api;
+//import io.swagger.annotations.ApiOperation;
+//import org.springframework.beans.factory.annotation.Autowired;
+//import org.springframework.web.bind.annotation.PostMapping;
+//import org.springframework.web.bind.annotation.RequestBody;
+//import org.springframework.web.bind.annotation.RequestMapping;
+//import org.springframework.web.bind.annotation.RestController;
+//
+//
+///**
+// * @Description: 用户账号API
+// * @author: gaodm
+// * @time: 2018/8/2 13:56
+// */
+//@RestController
+//@Api(value = "用户账号API", tags = { "用户账号API" })
+//@RequestMapping("/sys/user")
+//@SuppressWarnings("unchecked")
+//public class UserLoginController {
+//
+//    @Autowired
+//    private TokenFacade tokenFacade;
+//    @Autowired
+//    private UserLoginFacade userFacade;
+//
+//    @ApiOperation(value = "登录获取jwt[by:gaodm]",
+//            notes = "username:用户名,必填<br>" +
+//                    "password:密码, 必填, 默认密码:dc483e80a7a0bd9ef71d8cf973673924<br> ")
+//    @PostMapping("/getJwt")
+//    @SysLogger("getJwt")
+//    public RespDTO<JwtDTO> getJwt(@RequestBody UserLoginVO userLoginVO) {
+//        JwtDTO data = userFacade.getJwt(userLoginVO.getUsername(), userLoginVO.getPassword());
+//        return RespDTO.onSuc(data);
+//    }
+//
+//
+//
+//
+//
+//
+//
+//}

+ 1 - 1
user-auth/src/main/java/com/lantone/userauth/service/impl/UserServiceImpl.java

@@ -34,7 +34,7 @@ public class UserServiceImpl implements UserDetailsService {
     public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         String clientId = request.getParameter("client_id");
         UserDto userDto = null;
-        if (AuthConstant.ADMIN_CLIENT_ID.equals(clientId)) {
+        if (AuthConstant.USER_ADMIN_CLIENT_ID.equals(clientId)) {
             userDto = adminService.loadUserByUsername(username);
         }
         if (userDto == null) {