浏览代码

shiro调整

laowo 3 年之前
父节点
当前提交
ecf78f99ed

+ 17 - 4
pom.xml

@@ -12,8 +12,14 @@
     <parent>
         <artifactId>spring-boot-starter-parent</artifactId>
         <groupId>org.springframework.boot</groupId>
-        <version>2.1.4.RELEASE</version>
+        <version>2.1.5.RELEASE</version>
     </parent>
+<!--    <parent>-->
+<!--        <groupId>org.springframework.boot</groupId>-->
+<!--        <artifactId>spring-boot-starter-parent</artifactId>-->
+<!--        <version>2.3.5.RELEASE</version>-->
+<!--        <relativePath/>-->
+<!--    </parent>-->
     <dependencies>
         <!--spring配置-->
         <dependency>
@@ -75,18 +81,25 @@
             <scope>test</scope>
         </dependency>
         <!--shiro依赖-->
+        <!--shiro-->
         <dependency>
             <groupId>org.apache.shiro</groupId>
-            <artifactId>shiro-spring</artifactId>
-            <version>1.5.2</version>
+            <artifactId>shiro-spring-boot-starter</artifactId>
+            <version>1.7.1</version>
         </dependency>
+        <!-- shiro-redis -->
         <dependency>
             <groupId>org.crazycake</groupId>
             <artifactId>shiro-redis</artifactId>
             <version>3.1.0</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>org.apache.shiro</groupId>
+                    <artifactId>shiro-core</artifactId>
+                </exclusion>
+            </exclusions>
         </dependency>
 
-
         <dependency>
             <groupId>org.apache.commons</groupId>
             <artifactId>commons-lang3</artifactId>

+ 1 - 1
src/main/java/com/usky/config/CorsConfig.java

@@ -36,7 +36,7 @@ public class CorsConfig implements WebMvcConfigurer {
 
     @SuppressWarnings({"rawtypes", "unchecked"})
     @Bean
-    @Order(1)//设置filter执行的顺序
+    @Order(-1)//设置filter执行的顺序
     public FilterRegistrationBean filterRegest() {
         FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
         filterRegistrationBean.setFilter(new XssFilter());

+ 0 - 104
src/main/java/com/usky/config/ShiroProperties.java

@@ -1,104 +0,0 @@
-package com.usky.config;
-
-import lombok.Data;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.stereotype.Component;
-
-/**
- * @author laowo
- * @version v1.0
- * @date 2021/8/19 17:24
- * @description TODO
- **/
-@Data
-@ConfigurationProperties(prefix = "shiro")
-@Component
-public class ShiroProperties {
-    /**
-     * shiro 常规设置
-     */
-    private User user = new User();
-    /**
-     * cookie设置
-     */
-    private Cookie cookie = new Cookie();
-    /**
-     * session设置
-     */
-    private Session session = new Session();
-
-    @Data
-    public static class User {
-        /**
-         * 登录地址
-         */
-        private String loginUrl;
-        /**
-         * 权限认证失败地址
-         */
-        private String unauthorizedUrl;
-        /**
-         * 首页地址
-         */
-        private String indexUrl;
-        /**
-         * 验证码开关
-         */
-        private Boolean captchaEnabled;
-        /**
-         * 验证码类型
-         */
-        private String captchaType;
-    }
-
-    @Data
-
-    public static class Cookie {
-        /**
-         * # 设置Cookie的域名 默认空,即当前访问的域名
-         */
-        private String domain;
-        /**
-         * 设置cookie的有效访问路径
-         */
-        private String path;
-        /**
-         * 设置HttpOnly属性
-         */
-        private Boolean httpOnly;
-        /**
-         * 设置Cookie的过期时间,天为单位
-         */
-        private int maxAge;
-        /**
-         * cipherKey
-         */
-        private String cipherKey;
-
-    }
-
-    @Data
-    static class Session {
-        /**
-         * Session超时时间,-1代表永不过期(默认30分钟)
-         */
-        private int expireTime;
-        /**
-         * 同步session到数据库的周期(默认1分钟)
-         */
-        private int dbSyncPeriod;
-        /**
-         * 相隔多久检查一次session的有效性,默认就是10分钟
-         */
-        private int validationInterval;
-        /**
-         * 同一个用户最大会话数,比如2的意思是同一个账号允许最多同时两个人登录(默认-1不限制)
-         */
-        private int maxSession;
-        /**
-         * 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户
-         */
-        private boolean kickoutAfter;
-    }
-}

+ 42 - 37
src/main/java/com/usky/config/redis/RedisConfig.java

@@ -13,51 +13,56 @@ import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
 import org.springframework.data.redis.serializer.RedisSerializer;
 import org.springframework.data.redis.serializer.StringRedisSerializer;
+
 import javax.annotation.Resource;
 
 /**
-* 开启缓存支持
-* @author zyf
+ * 开启缓存支持
+ *
  * @Return:
-*/
+ */
 @Slf4j
 @Configuration
 public class RedisConfig extends CachingConfigurerSupport {
 
-	@Resource
-	private LettuceConnectionFactory lettuceConnectionFactory;
-	/**
-	 * RedisTemplate配置
-	 * @param lettuceConnectionFactory
-	 * @return
-	 */
-	@Bean
-	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
-		log.info(" --- redis config init --- ");
-		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =jacksonSerializer();
-		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
-		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
-		RedisSerializer<?> stringSerializer = new StringRedisSerializer();
-		// key序列化
-		redisTemplate.setKeySerializer(stringSerializer);
-		// value序列化
-		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
-		// Hash key序列化
-		redisTemplate.setHashKeySerializer(stringSerializer);
-		// Hash value序列化
-		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
-		redisTemplate.afterPropertiesSet();
-		return redisTemplate;
-	}
-
-	private Jackson2JsonRedisSerializer jacksonSerializer() {
-		Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
-		ObjectMapper objectMapper = new ObjectMapper();
-		objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
-		objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
-		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
-		return jackson2JsonRedisSerializer;
-	}
+    @Resource
+    private LettuceConnectionFactory lettuceConnectionFactory;
+
+    /**
+     * RedisTemplate配置
+     *
+     * @param lettuceConnectionFactory
+     * @return
+     */
+    @Bean
+    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
+        log.info(" --- redis config init --- ");
+        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = jacksonSerializer();
+        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
+        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
+        RedisSerializer<?> stringSerializer = new StringRedisSerializer();
+        // key序列化
+        redisTemplate.setKeySerializer(stringSerializer);
+        // value序列化
+        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
+        // Hash key序列化
+        redisTemplate.setHashKeySerializer(stringSerializer);
+        // Hash value序列化
+        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
+        redisTemplate.afterPropertiesSet();
+        return redisTemplate;
+    }
+
+    private Jackson2JsonRedisSerializer jacksonSerializer() {
+        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
+        ObjectMapper objectMapper = new ObjectMapper();
+        objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
+        objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
+        return jackson2JsonRedisSerializer;
+    }
+
+
 
 
 }

+ 0 - 97
src/main/java/com/usky/config/shiro/MyRealm.java

@@ -1,97 +0,0 @@
-package com.usky.config.shiro;
-
-
-import com.usky.entity.sys.vo.SysUserVO;
-
-import com.usky.service.sys.menuService.MenuService;
-import com.usky.service.sys.user.LoginService;
-import com.usky.service.sys.user.UserService;
-import com.usky.utils.ShiroUtils;
-import org.apache.shiro.authc.*;
-import org.apache.shiro.authz.AuthorizationInfo;
-import org.apache.shiro.authz.SimpleAuthorizationInfo;
-import org.apache.shiro.cache.Cache;
-import org.apache.shiro.realm.AuthorizingRealm;
-import org.apache.shiro.subject.PrincipalCollection;
-import org.apache.shiro.util.ByteSource;
-import org.apache.shiro.util.SimpleByteSource;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.stereotype.Component;
-
-import java.util.HashSet;
-import java.util.Set;
-
-
-/**
- * @author laowo
- */
-@Component
-public class MyRealm extends AuthorizingRealm {
-
-    @Autowired
-    @Lazy
-    private LoginService loginService;
-    @Autowired
-    @Lazy
-    private UserService userService;
-    @Autowired
-    @Lazy
-    private MenuService menuService;
-    //获取权限信息的方法
-    @Override
-    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
-        SysUserVO user = ShiroUtils.getSysUserVo();
-        // 角色列表
-        Set<String> roles;
-        // 功能列表
-        Set<String> menus;
-        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
-        // 管理员拥有所有权限
-        if (user.isAdmin()) {
-            info.addRole("admin");
-            info.addStringPermission("*:*:*");
-        } else {
-
-            roles = userService.queryRoleKeys(user.getUserId());
-                 menus = menuService.qyeryPermsByUserId(user.getUserId());
-            // 角色加入AuthorizationInfo认证对象
-            info.setRoles(roles);
-            // 权限加入AuthorizationInfo认证对象
-            info.setStringPermissions(menus);
-        }
-        return info;
-    }
-
-    //登录认证
-    @Override
-    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
-        //token是封装好的用户提交的用户名密码
-        String username = ((UsernamePasswordToken) token).getUsername();
-        //获取用户
-        SysUserVO user = loginService.findUserByUsername(username);
-        if (user == null) {
-            return null;
-        } else {
-            //封装AuthenticationInfo
-            ByteSource bsSalt = new SimpleByteSource(user.getSalt());
-            return new SimpleAuthenticationInfo(user, user.getPassword(), bsSalt, getName());
-        }
-    }
-
-
-    /**
-     * 清理所有用户授权信息缓存
-     */
-    public void clearAllCachedAuthorizationInfo()
-    {
-        Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
-        if (cache != null)
-        {
-            for (Object key : cache.keys())
-            {
-                cache.remove(key);
-            }
-        }
-    }
-}

+ 0 - 78
src/main/java/com/usky/config/shiro/MyRedisSerializer.java

@@ -1,78 +0,0 @@
-package com.usky.config.shiro;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.data.redis.serializer.RedisSerializer;
-import org.springframework.data.redis.serializer.SerializationException;
- 
-import java.io.*;
- 
-/**
- * 重写序列化 序列化为字节码
- */
-public class MyRedisSerializer implements RedisSerializer {
-
-    private static Logger logger = LoggerFactory.getLogger(MyRedisSerializer.class);
-
-    public static boolean isEmpty(byte[] data) {
-        return (data == null || data.length == 0);
-    }
-
-    /**
-     * 序列化
-     * @param object
-     * @return
-     * @throws SerializationException
-     */
-    @Override
-    public byte[] serialize(Object object) throws SerializationException {
-        byte[] result = null;
-
-        if (object == null) {
-            return new byte[0];
-        }
-        try (
-                ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128);
-                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream)
-        ){
-
-            if (!(object instanceof Serializable)) {
-                throw new IllegalArgumentException(MyRedisSerializer.class.getSimpleName() + " requires a Serializable payload " +
-                        "but received an object of type [" + object.getClass().getName() + "]");
-            }
-
-            objectOutputStream.writeObject(object);
-            objectOutputStream.flush();
-            result =  byteStream.toByteArray();
-        } catch (Exception ex) {
-            logger.error("Failed to serialize",ex);
-        }
-        return result;
-    }
-
-    /**
-     * 反序列化
-     * @param bytes
-     * @return
-     * @throws SerializationException
-     */
-    @Override
-    public Object deserialize(byte[] bytes) throws SerializationException {
-
-        Object result = null;
-
-        if (isEmpty(bytes)) {
-            return null;
-        }
-
-        try (
-                ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
-                ObjectInputStream objectInputStream = new ObjectInputStream(byteStream)
-        ){
-            result = objectInputStream.readObject();
-        } catch (Exception e) {
-            logger.error("Failed to deserialize",e);
-        }
-        return result;
-    }
-}

+ 0 - 265
src/main/java/com/usky/config/shiro/ShiroConfig.java

@@ -1,265 +0,0 @@
-package com.usky.config.shiro;
-
-import lombok.extern.slf4j.Slf4j;
-import org.apache.shiro.authc.credential.CredentialsMatcher;
-import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
-import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
-import org.apache.shiro.mgt.DefaultSubjectDAO;
-import org.apache.shiro.mgt.SecurityManager;
-import org.apache.shiro.spring.LifecycleBeanPostProcessor;
-import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
-import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
-import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
-import org.crazycake.shiro.IRedisManager;
-import org.crazycake.shiro.RedisCacheManager;
-import org.crazycake.shiro.RedisManager;
-import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-import org.springframework.context.annotation.DependsOn;
-import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
-import org.springframework.util.StringUtils;
-
-import javax.annotation.Resource;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * @author laowo
- */
-@Configuration
-@Slf4j
-public class ShiroConfig {
-//    @Resource
-//    private LettuceConnectionFactory lettuceConnectionFactory;
-//    @Bean
-//    public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
-//        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
-//        shiroFilterFactoryBean.setSecurityManager(securityManager);
-//        //登录
-//        shiroFilterFactoryBean.setLoginUrl("/sys/login");
-//        //控制 访问xx资源 需要xx权限
-//        Map<String, String> filterChainMap = new LinkedHashMap<>();
-//        //swagger接口权限 开放
-//        filterChainMap.put("/doc.html", "anon");
-//        filterChainMap.put("/webjars/**/**", "anon");
-//        filterChainMap.put("/swagger-ui.html", "anon");
-//        filterChainMap.put("/webjars/**", "anon");
-//        filterChainMap.put("/v2/**", "anon");
-//        filterChainMap.put("/swagger-resources/**", "anon");
-//        //退出
-//        filterChainMap.put("/logout", "logout");
-//        filterChainMap.put("/static/**", "anon");
-//        filterChainMap.put("/templates/**", "anon");
-//        //swagger接口权限 开放
-//        filterChainMap.put("/**", "authc");
-//        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
-//        return shiroFilterFactoryBean;
-//    }
-//    @Bean(name = "securityManager")
-//    public SecurityManager securityManager(@Qualifier("myRealm") MyRealm myRealm) {
-//        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
-//        // 设置realm.
-//        securityManager.setRealm(myRealm);
-//        securityManager.setCacheManager(redisCacheManager());
-//        // 自定义session管理 使用redis
-//        securityManager.setSessionManager(sessionManager());
-//        return securityManager;
-//    }
-//    @Bean(name = "myRealm")
-//    public MyRealm shiroRealm(@Qualifier("credentialsMatcher") CredentialsMatcher credentialsMatcher) {
-//        MyRealm shiroRealm = new MyRealm();
-//        shiroRealm.setCredentialsMatcher(credentialsMatcher);
-//        return shiroRealm;
-//    }
-//    /**
-//     * 凭证匹配器
-//     * @return
-//     */
-//    @Bean
-//    public CredentialsMatcher credentialsMatcher() {
-//        HashedCredentialsMatcher hashedMatcher = new HashedCredentialsMatcher();
-//        hashedMatcher.setHashAlgorithmName("md5");
-////        hashedMatcher.setHashIterations(1);
-//        return hashedMatcher;
-//    }
-//    @Bean
-//    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) {
-//        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
-//        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
-//        return authorizationAttributeSourceAdvisor;
-//    }
-//
-//    /**
-//     * 配置shiro redisManager
-//     * @return
-//     */
-//    public RedisManager redisManager() {
-//        RedisManager redisManager = new RedisManager();
-//        redisManager.setHost("47.111.81.118:6379");
-//        redisManager.setDatabase(1);
-//        redisManager.setTimeout(0);
-//        redisManager.setPassword(redisProperties.getPassword());
-//        return redisManager;
-//    }
-//    /**
-//     * cacheManager 缓存 redis实现
-//     * 使用的是shiro-redis开源插件
-//     * @return
-//     */
-//    @Bean
-//    public RedisCacheManager redisCacheManager() {
-//        RedisCacheManager redisCacheManager = new RedisCacheManager();
-//        redisCacheManager.setRedisManager(redisManager());
-//        redisCacheManager.setPrincipalIdFieldName("userId");
-//        return redisCacheManager;
-//    }
-//    /**
-//     * RedisSessionDAO shiro sessionDao层的实现 通过redis
-//     * 使用的是shiro-redis开源插件
-//     */
-////    @Bean
-//    public RedisSessionDAO redisSessionDAO() {
-//        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
-//        redisSessionDAO.setRedisManager(redisManager());
-//        return redisSessionDAO;
-//    }
-//    /**
-//     * shiro session的管理
-//     */
-//    @Bean
-//    public DefaultWebSessionManager sessionManager() {
-//        DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
-//        sessionManager.setGlobalSessionTimeout(redisProperties.getExpire());
-//        sessionManager.setSessionDAO(redisSessionDAO());
-//        return sessionManager;
-//    }
-
-    @Resource
-    LettuceConnectionFactory lettuceConnectionFactory;
-
-    /**
-     * Filter Chain定义说明
-     * <p>
-     * 1、一个URL可以配置多个Filter,使用逗号分隔
-     * 2、当设置多个过滤器时,全部验证通过,才视为通过
-     * 3、部分过滤器可指定参数,如perms,roles
-     */
-    @Bean("shiroFilter")
-    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
-        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
-        shiroFilterFactoryBean.setSecurityManager(securityManager);
-        // 拦截器
-        // 配置不会被拦截的链接 顺序判断
-        //控制 访问xx资源 需要xx权限
-        Map<String, String> filterChainMap = new LinkedHashMap<>();
-        //swagger接口权限 开放
-        filterChainMap.put("/doc.html", "anon");
-        filterChainMap.put("/v2/**", "anon");
-        filterChainMap.put("/webjars/**/**", "anon");
-        filterChainMap.put("/swagger-ui.html", "anon");
-        filterChainMap.put("/webjars/**", "anon");
-        filterChainMap.put("/swagger-resources/**", "anon");
-        filterChainMap.put("/druid/**", "anon");
-        filterChainMap.put("/swagger**/**", "anon");
-        //登录
-        shiroFilterFactoryBean.setLoginUrl("/sys/login");
-        //退出
-        filterChainMap.put("/logout", "logout");
-        filterChainMap.put("/static/**", "anon");
-        filterChainMap.put("/templates/**", "anon");
-        //swagger接口权限 开放
-        filterChainMap.put("/**", "authc");
-        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
-        return shiroFilterFactoryBean;
-    }
-
-    @Bean("securityManager")
-    public DefaultWebSecurityManager securityManager(MyRealm myRealm) {
-        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
-        myRealm.setCredentialsMatcher(credentialsMatcher());
-        securityManager.setRealm(myRealm);
-        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
-        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
-        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
-        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
-        securityManager.setSubjectDAO(subjectDAO);
-        //自定义缓存实现,使用redis
-        securityManager.setCacheManager(redisCacheManager());
-        return securityManager;
-    }
-
-        /**
-     * 凭证匹配器
-     * @return
-     */
-    @Bean
-    public CredentialsMatcher credentialsMatcher() {
-        HashedCredentialsMatcher hashedMatcher = new HashedCredentialsMatcher();
-        hashedMatcher.setHashAlgorithmName("md5");
-//        hashedMatcher.setHashIterations(1);
-        return hashedMatcher;
-    }
-
-
-    /**
-     * 下面的代码是添加注解支持
-     */
-    @Bean
-    @DependsOn("lifecycleBeanPostProcessor")
-    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
-        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
-        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
-        defaultAdvisorAutoProxyCreator.setUsePrefix(true);
-        defaultAdvisorAutoProxyCreator.setAdvisorBeanNamePrefix("_no_advisor");
-        return defaultAdvisorAutoProxyCreator;
-    }
-    @Bean
-    public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
-        return new LifecycleBeanPostProcessor();
-    }
-    @Bean
-    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
-        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
-        advisor.setSecurityManager(securityManager);
-        return advisor;
-    }
-
-    /**
-     * cacheManager 缓存 redis实现
-     * 使用的是shiro-redis开源插件
-     *
-     */
-    public RedisCacheManager redisCacheManager() {
-        log.info("===============(1)创建缓存管理器RedisCacheManager");
-        RedisCacheManager redisCacheManager = new RedisCacheManager();
-        redisCacheManager.setRedisManager(redisManager());
-        //redis中针对不同用户缓存(此处的id需要对应user实体中的id字段,用于唯一标识)
-     //   redisCacheManager.setPrincipalIdFieldName("id");
-        redisCacheManager.setPrincipalIdFieldName("userId");
-        //用户权限信息缓存时间
-        redisCacheManager.setExpire(200000);
-        return redisCacheManager;
-    }
-
-    /**
-     * 配置shiro redisManager
-     * 使用的是shiro-redis开源插件
-     *
-     */
-    @Bean
-    public IRedisManager redisManager() {
-        log.info("===============(2)创建RedisManager,连接Redis..");
-        IRedisManager manager;
-        RedisManager redisManager = new RedisManager();
-        redisManager.setHost(lettuceConnectionFactory.getHostName());
-        redisManager.setPort(lettuceConnectionFactory.getPort());
-        redisManager.setDatabase(1);
-        redisManager.setTimeout(0);
-        if (!StringUtils.isEmpty(lettuceConnectionFactory.getPassword())) {
-            redisManager.setPassword(lettuceConnectionFactory.getPassword());
-        }
-        manager = redisManager;
-        return manager;
-    }
-}

+ 0 - 72
src/main/java/com/usky/config/shiro/ShiroRedisSessionDao.java

@@ -1,72 +0,0 @@
-package com.usky.config.shiro;
-
-import org.apache.shiro.session.Session;
-import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.RedisTemplate;
-
-import java.io.Serializable;
-
-/**
- *
- */
-public class ShiroRedisSessionDao extends CachingSessionDAO {
-
-    public static final String SHIRO_SESSION_KEY = "shiro_session_key";
-
-    private Logger logger = LoggerFactory.getLogger(this.getClass());
-
-    @Autowired
-    private RedisTemplate redisTemplate; //spring-data-redis
-
-    @Override
-    protected void doUpdate(Session session) {
-        this.saveSession(session);
-    }
-
-    @Override
-    protected void doDelete(Session session) {
-        if (session == null || session.getId() == null) {
-            logger.error("session or session id is null");
-            return;
-        }
-        //根据session id删除session
-        redisTemplate.boundHashOps(SHIRO_SESSION_KEY).delete(session.getId());
-    }
-
-
-    @Override
-    protected Serializable doCreate(Session session) {
-        Serializable sessionId = this.generateSessionId(session);
-        this.assignSessionId(session, sessionId);
-        this.saveSession(session);
-        return sessionId;
-    }
-
-
-    @Override
-    protected Session doReadSession(Serializable sessionId) {
-        if (sessionId == null) {
-            logger.error("传入的 session id is null");
-            return null;
-        }
-        Object o = redisTemplate.boundHashOps(SHIRO_SESSION_KEY).get(sessionId);
-
-        return (Session) o;
-    }
-
-    /**
-     * 将session 保存进redis 中
-     *
-     * @param session 要保存的session
-     */
-    private void saveSession(Session session) {
-        if (session == null || session.getId() == null) {
-            logger.error("session or session id is null");
-            return;
-        }
-        redisTemplate.boundHashOps(SHIRO_SESSION_KEY).put(session.getId(), session);
-    }
-}

+ 10 - 4
src/main/java/com/usky/controller/login/LoginController.java

@@ -1,5 +1,6 @@
 package com.usky.controller.login;
 
+import com.usky.utils.AuthorizationUtils;
 import com.usky.utils.Result;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
@@ -29,13 +30,13 @@ public class LoginController {
     @ApiOperation(value = "用户登录")
     @ApiImplicitParams({
             @ApiImplicitParam(name = "loginName", value = "登录名", required = true, paramType = "query"),
-            @ApiImplicitParam(name = "password", value = "密码", required = true, paramType = "query")
+            @ApiImplicitParam(name = "passWord", value = "密码", required = true, paramType = "query")
     })
-    public Result<?> login(String loginName, String password) {
+    public Result<?> login(String loginName, String passWord) {
         try {
             //获取登录用户
             Subject subject = SecurityUtils.getSubject();
-            AuthenticationToken token = new UsernamePasswordToken(loginName, password);
+            AuthenticationToken token = new UsernamePasswordToken(loginName, passWord);
             subject.login(token);
             return Result.OK("登录成功");
         } catch (AuthenticationException e) {
@@ -47,7 +48,12 @@ public class LoginController {
         }
     }
 
+    @PostMapping("loginOut")
+    @ApiOperation(value = "用户退出")
+    public Result<?> loginOut() {
+     //   AuthorizationUtils.clearAllCachedAuthorizationInfo();
+        return Result.error("操作成功");
+    }
 
-  
 
 }

+ 0 - 4
src/main/java/com/usky/entity/sys/vo/SysUserVO.java

@@ -1,20 +1,16 @@
 package com.usky.entity.sys.vo;
 
-import com.fasterxml.jackson.annotation.JsonIgnore;
 import com.usky.entity.BaseEntity;
 import com.usky.entity.sys.SysRoleDTO;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
-import springfox.documentation.annotations.ApiIgnore;
 
-import javax.persistence.*;
 import javax.validation.constraints.NotBlank;
 import javax.validation.constraints.Size;
 import java.io.Serializable;
 import java.sql.Timestamp;
 import java.util.List;
-import java.util.Objects;
 
 /**
  * @author laowo

+ 6 - 0
src/main/java/com/usky/exception/GloableExceptionResolver.java

@@ -3,6 +3,7 @@ package com.usky.exception;
 import com.usky.utils.Result;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.shiro.ShiroException;
+import org.apache.shiro.UnavailableSecurityManagerException;
 import org.apache.shiro.authc.IncorrectCredentialsException;
 import org.apache.shiro.authc.LockedAccountException;
 import org.apache.shiro.authc.UnknownAccountException;
@@ -30,11 +31,13 @@ public class GloableExceptionResolver {
         log.error(e.getMessage(), e);
         return Result.error("操作失败," + e.getMessage());
     }
+
     @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
     public Result<?> HttpRequestMethodNotSupportedException(Exception e) {
         log.error(e.getMessage(), e);
         return Result.error("请求方式异常," + e.getMessage());
     }
+
     @ExceptionHandler(DataIntegrityViolationException.class)
     public Result<?> handleDataIntegrityViolationException(DataIntegrityViolationException e) {
         log.error(e.getMessage(), e);
@@ -59,7 +62,10 @@ public class GloableExceptionResolver {
             return Result.error("密码不正确");
         } else if (e instanceof AuthorizationException) {
             return Result.error("没有此操作权限");
+        } else if (e instanceof UnavailableSecurityManagerException) {
+            return Result.error("用户未登录!");
         }
+        System.out.println("e = " + e.getMessage());
         return Result.error("系统维护中");
 
     }

+ 1 - 0
src/main/java/com/usky/filter/XssFilter.java

@@ -28,6 +28,7 @@ public class XssFilter extends OncePerRequestFilter {
                     chain.doFilter(xssRequest, response);
                 }
             } catch (Exception e) {
+            //    System.out.println("e = " + e.getCause().getMessage());
                 logger.error("Xss过滤器,包装request对象失败");
                 chain.doFilter(request, response);
             }

+ 4 - 1
src/main/java/com/usky/mqtthandler/Mqtt2MessageHandler.java

@@ -3,6 +3,7 @@ package com.usky.mqtthandler;
 import com.usky.config.webScoket.WsSessionManager;
 import com.usky.constant.CommonConstant;
 import com.usky.service.mqtt.MqttService;
+import com.usky.utils.RedisUtil;
 import lombok.SneakyThrows;
 import lombok.extern.log4j.Log4j2;
 import net.sf.json.JSONObject;
@@ -26,6 +27,8 @@ public class Mqtt2MessageHandler implements MessageHandler {
 
     @Autowired
     private MqttService mqttService;
+    @Autowired
+    private RedisUtil redisUtil;
 
     @PostConstruct
     private void addFailEvent() {
@@ -38,7 +41,7 @@ public class Mqtt2MessageHandler implements MessageHandler {
     @ServiceActivator(inputChannel = "channel1")
     @Override
     public void handleMessage(Message<?> message) throws MessagingException {
-
+        Object o = redisUtil.get("15365185591");
         String payload = (String) message.getPayload();
         if (isJsonObject(payload)) {
             JSONObject data = JSONObject.fromObject(payload);

+ 4 - 3
src/main/java/com/usky/utils/AuthorizationUtils.java

@@ -1,6 +1,7 @@
 package com.usky.utils;
 
-import com.usky.config.shiro.MyRealm;
+
+import com.usky.config.shiro.ShiroRealm;
 import org.apache.shiro.SecurityUtils;
 import org.apache.shiro.mgt.RealmSecurityManager;
 
@@ -21,9 +22,9 @@ public class AuthorizationUtils
     /**
      * 获取自定义Realm
      */
-    public static MyRealm getUserRealm()
+    public static ShiroRealm getUserRealm()
     {
         RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
-        return (MyRealm) rsm.getRealms().iterator().next();
+        return (ShiroRealm) rsm.getRealms().iterator().next();
     }
 }

+ 9 - 41
src/main/resources/application.yml

@@ -5,6 +5,7 @@ spring:
   redis:
     database: 0
     host: 47.111.81.118
+    #host: 172.16.120.184
     lettuce:
       pool:
         max-active: 8   #最大连接数据库连接数,设 0 为没有限制
@@ -75,14 +76,14 @@ mqtt:
     channel1:
       consumer-enable: true
       producer-enable: true
-   #   url: [tcp://124.71.175.91:1883]
-      url: [tcp://47.98.201.73:1883]
-      topics: [/1usky/10012/861050040560669/#,/1usky/10012/861050040560321/#,/1usky/10012/861050040533286/#]
+      url: [tcp://124.71.175.91:1883]
+     # url: [tcp://47.98.201.73:1883]
+      topics: [/2usky/10012/861050040560669/#,/2usky/10012/861050040560321/#,/2usky/10012/861050040533286/#]
       qos: [0,0,0]
-  #   username: wjzn2021
-  #   password: wjzn2021
-      username: usky
-      password: usky
+      username: wjzn2021
+      password: wjzn2021
+      #username: usky
+     # password: usky
       timeout: 60
       kep-alive-interval: 60
       async: true
@@ -99,40 +100,7 @@ mqtt:
         topic: will_topic
         payload: '{"id": "producer_client_test1"}'
         retained: false
-shiro:
-  user:
-    # 登录地址
-    loginUrl: /login
-    # 权限认证失败地址
-    unauthorizedUrl: /unauth
-    # 首页地址
-    indexUrl: /index
-    # 验证码开关
-    captchaEnabled: true
-    # 验证码类型 math 数组计算 char 字符
-    captchaType: math
-  cookie:
-    # 设置Cookie的域名 默认空,即当前访问的域名
-    domain:
-    # 设置cookie的有效访问路径
-    path: /
-    # 设置HttpOnly属性
-    httpOnly: true
-    # 设置Cookie的过期时间,天为单位
-    maxAge: 30
-    # 设置密钥,务必保持唯一性(生成方式,直接拷贝到main运行即可)Base64.encodeToString(CipherUtils.generateNewKey(128, "AES").getEncoded()) (默认启动生成随机秘钥,随机秘钥会导致之前客户端RememberMe Cookie无效,如设置固定秘钥RememberMe Cookie则有效)
-    cipherKey:
-  session:
-    # Session超时时间,-1代表永不过期(默认30分钟)
-    expireTime: 30
-    # 同步session到数据库的周期(默认1分钟)
-    dbSyncPeriod: 1
-    # 相隔多久检查一次session的有效性,默认就是10分钟
-    validationInterval: 10
-    # 同一个用户最大会话数,比如2的意思是同一个账号允许最多同时两个人登录(默认-1不限制)
-    maxSession: -1
-    # 踢出之前登录的/之后登录的用户,默认踢出之前登录的用户
-    kickoutAfter: false
+
 
 
 

+ 1 - 1
src/main/resources/logback-spring.xml

@@ -109,7 +109,7 @@
     <!-- root级别 DEBUG -->
     <root>
         <!-- 打印debug级别日志及以上级别日志 -->
-        <level value="info" />
+        <level value="INFO" />
         <!-- 控制台输出 -->
         <appender-ref ref="console" />
         <!-- 文件输出 -->

+ 0 - 18
src/main/test/java/com/usky/controller/mqtt/MqttTestControllerTest.java

@@ -1,18 +0,0 @@
-package com.usky.controller.mqtt;
-
-import com.usky.utils.RedisUtil;
-import org.junit.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.Map;
-
-public class MqttTestControllerTest extends BaseTest {
-    @Autowired
-    private RedisUtil redisUtil;
-
-    @Test
-    public void redisTest() {
-        Map<String,Object> sn = (Map<String, Object>) redisUtil.get("sn");
-        System.out.println("sn = " + sn);
-    }
-}