• shiro 框架下配置可匿名访问接口


    1.在 ShiroConfig 文件里面。

    shiroFilterFactoryBean 这个方法下
    LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();   注意只能是linkedHashMap
    filterChainDefinitionMap.put("/platform/exceptionInfo/**","anon"); //开放路径 和 anon是指不会被拦截的页面的路径
    filterChainDefinitionMap.put("/**", "authc");     //需要认证的路径  authc是需要认证才可访问


    2.如果这样还不行,报403的话,应该是接口本身上面还有权限验证。

    将这个注解注释掉即可

    3.ShiroConfig 全部内容

    package com.bootdo.system.config;
    
    import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
    import com.bootdo.common.config.Constant;
    import com.bootdo.common.redis.shiro.RedisCacheManager;
    import com.bootdo.common.redis.shiro.RedisManager;
    import com.bootdo.common.redis.shiro.RedisSessionDAO;
    import com.bootdo.system.filter.ApiFilter;
    import com.bootdo.system.filter.ShiroLoginFilter;
    import com.bootdo.system.shiro.CustomModularRealmAuthenticator;
    import com.bootdo.system.shiro.UserRealm;
    import com.bootdo.system.shiro.WeixinShiroRealm;
    
    //import org.apache.shiro.cache.CacheManager;
    import net.sf.ehcache.CacheManager;
    
    import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
    import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
    import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
    import org.apache.shiro.cache.ehcache.EhCacheManager;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.realm.Realm;
    import org.apache.shiro.session.SessionListener;
    import org.apache.shiro.session.mgt.eis.MemorySessionDAO;
    import org.apache.shiro.session.mgt.eis.SessionDAO;
    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.apache.shiro.web.servlet.SimpleCookie;
    import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.cache.ehcache.EhCacheCacheManager;
    import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.core.io.ClassPathResource;
    import org.springframework.util.StringUtils;
    import org.springframework.web.servlet.HandlerExceptionResolver;
    
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.Filter;
    
    /**
     * @author bootdo 1992lcg@163.com
     */
    @Configuration
    public class ShiroConfig {
        @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.cache.type}")
        private String cacheType ;
    
        @Value("${server.session-timeout}")
        private int tomcatTimeout;
        
        @Value("${spring.cache.ehcache.config}")
        private String EhCacheconfig ;
    
        @Bean
        public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
            return new LifecycleBeanPostProcessor();
        }
    
        /**
         * ShiroDialect,为了在thymeleaf里使用shiro的标签的bean
         *
         * @return
         */
        @Bean
        public ShiroDialect shiroDialect() {
            return new ShiroDialect();
        }
    
        @Bean
        ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
            ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
            shiroFilterFactoryBean.setSecurityManager(securityManager);
            //增加自定义过滤
            Map<String, Filter> filters = new HashMap();
    
            filters.put("jwt", new ApiFilter());
            shiroFilterFactoryBean.setFilters(filters);
            
            //shiroFilterFactoryBean.setLoginUrl("/login");
            shiroFilterFactoryBean.setSuccessUrl("/index");
            shiroFilterFactoryBean.setUnauthorizedUrl("/403");
            LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
            filterChainDefinitionMap.put("/platform/exceptionInfo/**","anon");
            filterChainDefinitionMap.put("/login","anon");
            filterChainDefinitionMap.put("/getSessionKey", "anon");
            filterChainDefinitionMap.put("/getUserinfo", "anon");
            filterChainDefinitionMap.put("/refrehtoken", "anon");
            filterChainDefinitionMap.put("/css/**", "anon");
            filterChainDefinitionMap.put("/js/**", "anon");
            filterChainDefinitionMap.put("/fonts/**", "anon");
            filterChainDefinitionMap.put("/img/**", "anon");
            filterChainDefinitionMap.put("/images/**","anon");
            filterChainDefinitionMap.put("/docs/**", "anon");
            filterChainDefinitionMap.put("/druid/**", "anon");
            filterChainDefinitionMap.put("/upload/**", "anon");
            filterChainDefinitionMap.put("/files/**", "anon");
            filterChainDefinitionMap.put("/logout", "logout");
          //配置记住我或认证通过可以访问的地址
            filterChainDefinitionMap.put("/api/**", "jwt");
            filterChainDefinitionMap.put("/", "anon");
            filterChainDefinitionMap.put("/blog", "anon");
            filterChainDefinitionMap.put("/blog/open/**", "anon");
            filterChainDefinitionMap.put("/defaultKaptcha/**", "anon");
            filterChainDefinitionMap.put("/weixin", "anon");
            filterChainDefinitionMap.put("/wxbind/**", "anon");
            filterChainDefinitionMap.put("/wx/**", "jwt");//暂时开放
            filterChainDefinitionMap.put("/layui/**", "anon");//
            filterChainDefinitionMap.put("/**", "authc");
            shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
            return shiroFilterFactoryBean;
        }
    
    
        @Bean
        public SecurityManager securityManager() {
            DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
            //设置realm.
            
            
            //设置realm.
            securityManager.setAuthenticator(modularRealmAuthenticator());
            List<Realm> realms = new ArrayList<>();
            //添加多个Realm
           
            realms.add(userRealm());
            realms.add(jwtShiroRealm());
            
            
            securityManager.setRealms(realms);
            
            
            // 自定义缓存实现 使用redis
            if (Constant.CACHE_TYPE_REDIS.equals(cacheType)) {
                securityManager.setCacheManager(rediscacheManager());
            } else {
                securityManager.setCacheManager(ehCacheManager());
            }
            securityManager.setSessionManager(sessionManager());
            return securityManager;
        }
        /**
         * 系统自带的Realm管理,主要针对多realm
         * */
        @Bean
        public ModularRealmAuthenticator modularRealmAuthenticator(){
             //自己重写的ModularRealmAuthenticator
            Map<String, Object> shiroAuthenticatorRealms = new HashMap<>();
            shiroAuthenticatorRealms.put("adminShiroRealm", userRealm());
            shiroAuthenticatorRealms.put("jwtShiroRealm", jwtShiroRealm());
           CustomModularRealmAuthenticator modularRealmAuthenticator = new CustomModularRealmAuthenticator();
           modularRealmAuthenticator.setDefinedRealms(shiroAuthenticatorRealms);
           modularRealmAuthenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy());
           return modularRealmAuthenticator;
        }
    
        
        /**
         * token身份认证realm;
         * @return
         */
        @Bean(name="jwtShiroRealm")
        public WeixinShiroRealm jwtShiroRealm(){
            WeixinShiroRealm jwtShiroRealm = new WeixinShiroRealm();
            jwtShiroRealm.setCredentialsMatcher(customHashedCredentialsMatcher());
            return new WeixinShiroRealm();
        }
       
        @Bean(name = "customHashedCredentialsMatcher")
        public HashedCredentialsMatcher customHashedCredentialsMatcher(){
            //logger.debug("ShiroConfiguration.adminHashedCredentialsMatcher()");
            HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
            hashedCredentialsMatcher.setHashAlgorithmName("md5");//散列算法:这里使用MD5算法;
            hashedCredentialsMatcher.setHashIterations(1);//散列的次数,当于 m比如散列两次,相d5("");
            return hashedCredentialsMatcher;
        }
    
        @Bean
        UserRealm userRealm() {
            UserRealm userRealm = new UserRealm();
            return userRealm;
        }
    
        /**
         * 开启shiro aop注解支持.
         * 使用代理方式;所以需要开启代码支持;
         *
         * @param securityManager
         * @return
         */
        @Bean
        public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
            AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
            authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
            return authorizationAttributeSourceAdvisor;
        }
    
        /**
         * 配置shiro redisManager
         *
         * @return
         */
        @Bean
        public RedisManager redisManager() {
            RedisManager redisManager = new RedisManager();
            redisManager.setHost(host);
            redisManager.setPort(port);
            redisManager.setExpire(tomcatTimeout);// 配置缓存过期时间
            redisManager.setTimeout(timeout);
            if (!StringUtils.isEmpty(password)) {
                redisManager.setPassword(password);
            }
            return redisManager;
        }
    
        /**
         * cacheManager 缓存 redis实现
         * 使用的是shiro-redis开源插件
         *
         * @return
         */
        public RedisCacheManager rediscacheManager() {
            RedisCacheManager redisCacheManager = new RedisCacheManager();
            redisCacheManager.setRedisManager(redisManager());
            return redisCacheManager;
        }
    
    
        /**
         * RedisSessionDAO shiro sessionDao层的实现 通过redis
         * 使用的是shiro-redis开源插件
         */
        @Bean
        public RedisSessionDAO redisSessionDAO() {
            RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
            redisSessionDAO.setRedisManager(redisManager());
            return redisSessionDAO;
        }
    
        @Bean
        public SessionDAO sessionDAO() {
            if (Constant.CACHE_TYPE_REDIS.equals(cacheType)) {
                return redisSessionDAO();
            } else {
                return new MemorySessionDAO();
            }
        }
    
        /**
         * shiro session的管理
         */
        @Bean
        public DefaultWebSessionManager sessionManager() {
            DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
            sessionManager.setGlobalSessionTimeout(tomcatTimeout * 1000);
            sessionManager.setSessionDAO(sessionDAO());
            Collection<SessionListener> listeners = new ArrayList<SessionListener>();
            listeners.add(new BDSessionListener());
            sessionManager.setSessionListeners(listeners);
            sessionManager.setSessionIdUrlRewritingEnabled(false);
            SimpleCookie simpleCookie= new SimpleCookie();
            simpleCookie.setName( Constant.SYSTEM_NAME+".session.id");
            sessionManager.setSessionIdCookie(simpleCookie);
            return sessionManager;
        }
    
        @Bean
        public EhCacheManager ehCacheManager() {
            EhCacheManager em = new EhCacheManager();
            em.setCacheManagerConfigFile(EhCacheconfig);
            //em.setCacheManager(cacheManager());
            return em;
        }
    
        @Bean("cacheManager2")
        CacheManager cacheManager(){
            return CacheManager.create();
        }
    
        @Bean  
        public ShiroLoginFilter shiroLoginFilter(){  
            return new ShiroLoginFilter();  
        }  
    }
    下班记得打卡
  • 相关阅读:
    su和sudo命令详解
    JS线程Web worker
    Navicat 批处理 自动备份数据库
    MySql【Error笔记】
    vue入门
    动态库
    环境变量
    cmake_learn
    自动编译
    网络编程
  • 原文地址:https://www.cnblogs.com/onlyzhangmeng/p/15439662.html
Copyright © 2020-2023  润新知