美文网首页
Springboot_Shiro_redis集成

Springboot_Shiro_redis集成

作者: bboymonk | 来源:发表于2017-05-19 15:46 被阅读0次

    导入依赖:

    <dependency>
                <groupId>org.crazycake</groupId>
                <artifactId>shiro-redis</artifactId>
                <version>2.4.2.1-RELEASE</version>
    </dependency>
    <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>1.3.2</version>
    </dependency>
    <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>1.3.2</version>
    </dependency>
    <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>1.3.2</version>
    </dependency>
    

    ShiroConfig配置:

    package com.pd.gch.security;
    
    import org.apache.log4j.Logger;
    import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
    import org.apache.shiro.spring.LifecycleBeanPostProcessor;
    import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
    import org.apache.shiro.web.filter.authc.AnonymousFilter;
    import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
    import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
    import org.crazycake.shiro.RedisCacheManager;
    import org.crazycake.shiro.RedisManager;
    import org.crazycake.shiro.RedisSessionDAO;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.DependsOn;
    import org.springframework.web.filter.DelegatingFilterProxy;
    
    import javax.servlet.DispatcherType;
    import javax.servlet.Filter;
    import java.util.HashMap;
    import java.util.Map;
    
    @Configuration
    public class ShiroConfig {
    
        Logger logger = Logger.getLogger(ShiroConfig.class);
    
        private  final  String host  = "120.25.176.86";
    
        private final int port =6379;
    
        private final   int timeout =0;
    
        private final   String password ="go2hell";
    
    
    
        /**
         * FilterRegistrationBean
         * @return
         */
        @Bean
        public FilterRegistrationBean filterRegistrationBean() {
            FilterRegistrationBean filterRegistration = new FilterRegistrationBean();
            filterRegistration.setFilter(new DelegatingFilterProxy("shiroFilter"));
            filterRegistration.setEnabled(true);
            filterRegistration.addUrlPatterns("/admin/*");
            filterRegistration.setDispatcherTypes(DispatcherType.REQUEST);
            return filterRegistration;
        }
    
        /**
         * @see ShiroFilterFactoryBean
         * @return
         */
        @Bean(name = "shiroFilter")
        public ShiroFilterFactoryBean shiroFilter(){
            ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
            bean.setSecurityManager(securityManager());
            bean.setLoginUrl("/admin_index/toLogin");
            bean.setUnauthorizedUrl("/unauthor");
    
            Map<String, Filter>filters = new HashMap();
            filters.put("resourceCheckFilter", resourceCheckFilter());
            filters.put("anon", new AnonymousFilter());
            bean.setFilters(filters);
    
            Map<String, String> chains = new HashMap();
            chains.put("/**/login", "anon");
            chains.put("/**/toLogin","anon");
            chains.put("/**/logout", "logout");
            chains.put("/admin/**", "authc,resourceCheckFilter");
            bean.setFilterChainDefinitionMap(chains);
            return bean;
        }
    
        /**
         * @see org.apache.shiro.mgt.SecurityManager
         * @return
         */
        @Bean(name="securityManager")
        public DefaultWebSecurityManager securityManager() {
            DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
            manager.setRealm(customShiroRealm());
            manager.setCacheManager(redisCacheManager());
            manager.setSessionManager(defaultWebSessionManager());
            return manager;
        }
    
        /**
         * @see DefaultWebSessionManager
         * @return
         */
        @Bean(name="sessionManager")
        public DefaultWebSessionManager defaultWebSessionManager() {
            DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
            sessionManager.setCacheManager(redisCacheManager());
            sessionManager.setGlobalSessionTimeout(1800000);
            sessionManager.setDeleteInvalidSessions(true);
            sessionManager.setSessionValidationSchedulerEnabled(true);
            sessionManager.setDeleteInvalidSessions(true);
            return sessionManager;
        }
    
        /**
         * @see CustomShiroRealm--->AuthorizingRealm
         * @return
         */
        @Bean
        @DependsOn(value="lifecycleBeanPostProcessor")
        public CustomShiroRealm customShiroRealm() {
            CustomShiroRealm customShiroRealm = new CustomShiroRealm();
            customShiroRealm.setCacheManager(redisCacheManager());
            customShiroRealm.setCredentialsMatcher(hashMatcher());
            return customShiroRealm;
        }
    
        @Bean
        public ResourceCheckFilter resourceCheckFilter() {
            ResourceCheckFilter resourceCheckFilter=new ResourceCheckFilter();
            resourceCheckFilter.setErrorUrl("/common/errorURL.html");
            return resourceCheckFilter;
        }
    
    //    @Bean
    //    public EhCacheManager cacheManager() {
    //        EhCacheManager cacheManager = new EhCacheManager();
    ////        cacheManager.setCacheManagerConfigFile("classpath:/conf/ehcache.xml");
    //        return cacheManager;
    //    }
    
    
        @Bean
        public RedisManager redisManager(){
            RedisManager redisManager =new RedisManager();
            redisManager.setHost(host);
            redisManager.setPassword(password);
            redisManager.setPort(port);
            redisManager.setTimeout(timeout);
            redisManager.setExpire(60*30);
            redisManager.init();
            return redisManager;
        }
    
    
        @Bean
        public RedisSessionDAO redisSessionDAO(){
            RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
            redisSessionDAO.setRedisManager(redisManager());
            return redisSessionDAO;
        }
    
        @Bean
        public DefaultWebSessionManager sessionManager(){
            DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
            defaultWebSessionManager.setSessionDAO(redisSessionDAO());
            return defaultWebSessionManager;
        }
    
    
        @Bean
        public RedisCacheManager redisCacheManager(){
            RedisCacheManager redisCacheManager = new RedisCacheManager();
            redisCacheManager.setRedisManager(redisManager());
            logger.error("===================");
            logger.error("开始加载redisCacheManager");
            logger.error("===================");
            return redisCacheManager;
        }
    
        @Bean
        public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
            return new LifecycleBeanPostProcessor();
        }
    
    
        @Bean("hashMatcher")
        public HashedCredentialsMatcher hashMatcher(){
            HashedCredentialsMatcher hashedCredentialsMatcher =new HashedCredentialsMatcher();
            hashedCredentialsMatcher.setHashAlgorithmName("md5");
            return  hashedCredentialsMatcher;
        }
    
    }
    

    Realm配置:

    package com.pd.gch.security;
    
    
    import com.pd.gch.commpents.ShiroKit;
    import com.pd.gch.moudles.admin.model.Admin;
    import com.pd.gch.moudles.admin.model.Resources;
    import com.pd.gch.moudles.admin.model.Role;
    import com.pd.gch.moudles.admin.service.AdminService;
    import com.pd.gch.moudles.admin.service.ResourcesService;
    import com.pd.gch.moudles.admin.service.RoleService;
    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.apache.shiro.subject.SimplePrincipalCollection;
    import org.apache.shiro.util.ByteSource;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    
    public class CustomShiroRealm extends AuthorizingRealm {
    
        @Autowired
        private RoleService roleService;
        @Autowired
        private ResourcesService resourcesService;
        @Autowired
        private AdminService adminService;
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            Admin admin = (Admin) principalCollection.getPrimaryPrincipal();
            Long uid = admin.getId();
            List<Role> roleList = roleService.getRoleByUid(uid);
            List<Resources> resourcesList = resourcesService.getResByUid(uid);
            Set<String> permissions =new HashSet<String>();
            Set<String> roles = new HashSet<String>() ;
            for(Role role:roleList){
                roles.add(role.getSn());
            }
            for(Resources res : resourcesList){
                permissions.add(res.getUrl());
            }
            SimpleAuthorizationInfo simpleAuthenticationInfo = new SimpleAuthorizationInfo();
            simpleAuthenticationInfo.setRoles(roles);
            simpleAuthenticationInfo.setStringPermissions(permissions);
            return simpleAuthenticationInfo;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            String username = authenticationToken.getPrincipal().toString();
            String password = new String((char[]) authenticationToken.getCredentials());
            Admin admin = adminService.login(username, ShiroKit.md5(password,username));
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(admin,admin.getPassword(),getName());
            info.setCredentialsSalt(ByteSource.Util.bytes(admin.getLoginName()));
            return info;
        }
    
        @Override
        protected void clearCachedAuthorizationInfo(PrincipalCollection principals) {
            super.clearCachedAuthorizationInfo(principals);
        }
    
        @Override
        protected void clearCachedAuthenticationInfo(PrincipalCollection principals) {
            Admin admin = ((Admin) principals.getPrimaryPrincipal());
            SimplePrincipalCollection spc = new SimplePrincipalCollection(admin.getLoginName(), getName());
            super.clearCachedAuthenticationInfo(spc);
        }
    }
    

    ShiroKit:

    package com.pd.gch.commpents;
    
    import com.pd.gch.moudles.admin.model.Admin;
    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.crypto.hash.Md5Hash;
    import org.apache.shiro.subject.Subject;
    
    public class ShiroKit {
        public static String md5(String password,String salt) {
            String p = null;
            p = new Md5Hash(password, salt).toHex();
            return p;
        }
    
       public static Admin getShiroAdmin(){
           Subject subject = SecurityUtils.getSubject();
          return  (Admin) subject.getPrincipal();
       }
    
        public static void removeShiroSession(){
            Subject subject = SecurityUtils.getSubject();
            subject.getSession().stop();
        }
    }
    

    Controller里使用:

    @Controller("admin")
    @RequestMapping("admin/")
    public class AdminController extends BaseController {
        private static final Logger logger = Logger.getLogger(AdminController.class);
        @Autowired
        private AdminService adminService;
        @Autowired
        private RefAdminGroupService refAdminGroupService;
        @Autowired
        private RefUserRoleService refUserRoleService;
    
        /**
         * @param oldPwd
         * @param newPwd
         * @return
         */
        @ResponseBody
        @PostMapping(value = "pwd.json",produces = {"application/json;charset=UTF-8"})
        public String pwd(String oldPwd,String newPwd){
            Admin currentAdmin =ShiroKit.getShiroAdmin();
            if(currentAdmin==null){
                return SUCCESS_FAIL_N(false,null,"10040");
            }else if(StringUtils.isEmpty(newPwd)||StringUtils.isEmpty(oldPwd)){
                return SUCCESS_FAIL_N(false,null,"10044");
            }else if(!ShiroKit.md5(oldPwd,currentAdmin.getName()).equals(currentAdmin.getPassword())){
                return SUCCESS_FAIL_N(false,null,"10041");
            }
            try {
                    currentAdmin.setPassword(ShiroKit.md5(newPwd,currentAdmin.getName()));
                    currentAdmin.setUpdateTime(new Date());
                    currentAdmin.setOperator(currentAdmin.getName());
                    currentAdmin.setOperatorId(currentAdmin.getId());
                    adminService.updateByPrimaryKeySelective(currentAdmin);
                    ShiroKit.removeShiroSession();
                    return SUCCESS_FAIL_N(true,"10042",null);
            }catch (Exception e){
                logger.error("修改密码失败",e);
                return SUCCESS_FAIL_N(false,null,"10043");
            }
        }
    

    理论来源可以参考:http://www.cnblogs.com/learnhow/p/5694876.html

    相关文章

      网友评论

          本文标题:Springboot_Shiro_redis集成

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