美文网首页java
springboot整合shiro和redis

springboot整合shiro和redis

作者: 星钻首席小管家 | 来源:发表于2020-08-07 10:07 被阅读0次

    1.shiro相关依赖

            <dependency>
              <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.3.2</version>
            </dependency>
            <dependency>
                <groupId>org.crazycake</groupId>
                <artifactId>shiro-redis</artifactId>
                <version>3.2.3</version>
            </dependency>
    

    2.yml文件

    spring
            redis:
                database: 0
                host: 127.0.0.1
                port: 6379
                password:
                timeout: 6000ms
    shiro:
      anonList:
        - /index
        - /login
        - /validateCode
        - /logout
        - /403
    

    3.PassRealm.java

    public class PassRealm extends AuthorizingRealm {
    
        @Autowired PeopleService peopleService;
    
        @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            return null;
        }
    
        @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
                throws AuthenticationException {
    
            //加这一步的目的是在Post请求的时候会先进认证,然后在到请求
            if (authenticationToken.getPrincipal() == null) {
                return null;
            }
            //获取用户信息
            String name = authenticationToken.getPrincipal().toString();
            People people = new People();
            people.setPeopleName(name);
            JsonListResult<People> list = peopleService.selectList(people);
            if (ObjectUtils.isEmpty(list)) {
                //这里返回后会报出对应异常
                return null;
            } else {
                //这里验证authenticationToken和simpleAuthenticationInfo的信息
                people = list.getItems().get(0);
                //存入session
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();
                session.setAttribute("user",people);
                SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(name, people.getPeoplePassword(), getName());
                return simpleAuthenticationInfo;
            }
        }
    }
    

    4.MyFormAuthenticationFilter.java

    public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
        private Logger log = LoggerFactory.getLogger(this.getClass());
        @Override
        protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
            // String loginUrl = this.getLoginUrl();
            // WebUtils.issueRedirect(request, response, loginUrl);
            // throw new AuthenticationException("未登录或登录超时");
            log.error("未登录或登录超时");
            HttpServletResponse response_ = (HttpServletResponse) response;
            response_.setStatus(403);
            response_.setCharacterEncoding("UTF-8");
            response_.setContentType("application/json; charset=utf-8");
            PrintWriter out = null ;
            try{
                JSONObject res = new JSONObject();
                res.put("status",false);
                res.put("message","未登录或登录超时");
                out = response.getWriter();
                out.append(res.toString());
            }
            catch (Exception e){
                log.error("",e);
            }
        }
    }
    

    5.ShiroAnonConfigYml.java

    @Component
    @PropertySource("classpath:application.yml")
    @ConfigurationProperties(prefix = "shiro")
    @Data
    public class ShiroAnonConfigYml {
        private List<String> anonList;
    }
    

    6.shiroConfig.java

    @Configuration
    public class shiroConfig {
    
        @Value("${spring.redis.host}")
        private String host;
    
        @Value("${spring.redis.port}")
        private int port;
    
        @Autowired
        private ShiroAnonConfigYml shiroAnonConfigYml;
    
        @Bean("shiroFilter")
        public ShiroFilterFactoryBean shirFilter(SessionsSecurityManager securityManager) {
            ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
            shiroFilterFactoryBean.setSecurityManager(securityManager);
            //拦截器.
            Map<String,String> filterChainDefinitionMap = new LinkedHashMap<String,String>();
            // 配置不会被拦截的链接 顺序判断
            List<String> anonList = shiroAnonConfigYml.getAnonList();
            for(String anon:anonList){
                filterChainDefinitionMap.put(anon, "anon");
            }
    
            //配置退出 过滤器,其中的具体的退出代码Shiro已经替我们实现了
            filterChainDefinitionMap.put("/logout", "logout");
            //配置静态资源可以匿名访问
            //filterChainDefinitionMap.put("/static/**", "anon");
            filterChainDefinitionMap.put("/css/**", "anon");
            filterChainDefinitionMap.put("/img/**", "anon");
            //<!-- 过滤链定义,从上向下顺序执行,一般将/**放在最为下边 -->:这是一个坑呢,一不小心代码就不好使了;
            //<!-- authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问-->
            filterChainDefinitionMap.put("/**", "authc");
            // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面
            shiroFilterFactoryBean.setLoginUrl("/user/403");
            // 登录成功后要跳转的链接
            //shiroFilterFactoryBean.setSuccessUrl("/index");
    
            //未授权界面;
            shiroFilterFactoryBean.setUnauthorizedUrl("/user/403");
            shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
            MyFormAuthenticationFilter formAuthenticationFilter = new MyFormAuthenticationFilter();
            shiroFilterFactoryBean.getFilters().put("authc", formAuthenticationFilter);
            return shiroFilterFactoryBean;
        }
    
        @Bean
        public SessionsSecurityManager securityManager(SessionManager sessionManager){
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            securityManager.setRealm(passRealm());
            securityManager.setSessionManager(sessionManager);
            return securityManager;
        }
    
        @Bean
        public PassRealm passRealm(){
            PassRealm passRealm = new PassRealm();
            return passRealm;
        }
    
        @Bean
        public SessionManager sessionManager(RedisSessionDAO redisSessionDAO){
            DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
            SimpleCookie jsid = new SimpleCookie("jsid");
            jsid.setPath("/");
            sessionManager.setSessionIdCookie(jsid);
            sessionManager.setGlobalSessionTimeout(3000);
            sessionManager.setSessionDAO(redisSessionDAO);
            return sessionManager;
        }
    
        /**
         * RedisSessionDAO shiro sessionDao层的实现 通过redis
         */
        @Bean
        public RedisSessionDAO redisSessionDAO() {
            RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
            redisSessionDAO.setRedisManager(redisManager());
            return redisSessionDAO;
        }
        /**
         * 配置shiro redisManager
         *
         * @return
         */
        public RedisManager redisManager() {
            RedisManager redisManager = new RedisManager();
            redisManager.setHost(host+":"+port);
            redisManager.setTimeout(10*1000);
    //        if (!StringUtils.isEmpty(this.password)){
    //            redisManager.setPassword(password);
    //        }
            return redisManager;
        }
    
        @Bean
        public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator(){
            DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
            advisorAutoProxyCreator.setProxyTargetClass(true);
            return advisorAutoProxyCreator;
        }
        @Bean
        public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SessionsSecurityManager securityManager){
            AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
            authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
            return authorizationAttributeSourceAdvisor;
        }
    
    
    }
    

    7.CurrentUser.java

    @Slf4j
    public class CurrentUser {
    
        public static User getUser() {
            Subject subject = SecurityUtils.getSubject();
            Map<String, Object> map = (Map<String, Object>) SerializeUtils.deserialize((byte[]) subject.getSession().getAttribute("user"));
            if(map !=null){
                try {
                    User user = new User();
                    //map转对象
                    BeanUtils.populate(user, map);
                    return user;
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                    log.error(e.getMessage());
                } catch (InvocationTargetException e) {
                    log.error(e.getMessage());
                }
            }
            return null;
        }
    
        public static long getUserId(){
            return getUser() != null ? getUser().getId() : 0 ;
        }
    
        public static String getUserCenterId(){
            return getUser() != null ? getUser().getCenterUserId() : null ;
        }
    }
    

    相关文章

      网友评论

        本文标题:springboot整合shiro和redis

        本文链接:https://www.haomeiwen.com/subject/suzxdktx.html