spring boot 与 shiro的简单整合使用

shrio官网https://shiro.apache.org/

Apache Shiro是一个功能强大且易于使用的Java安全框架,可执行身份验证,授权,加密和会话管理。借助Shiro易于理解的API,您可以快速轻松地保护任何应用程序 - 从最小的移动应用程序到最大的Web和企业应用程序。spring中也有自带的安全框架spring security。shrio是通过对其的再封装,实现了自己的一套全新架构。

正巧spring boot项目中也需要用到用户的身份验证以及权限控制,本来想用AOP自己写一套的,但是最终还是选择了shiro,通过与前辈的共同战斗,最终还是把它实现了出来。

1.直接上配置类:

/**
 * 
 * shiro配置类
 * @author wuzz
 * @Date   2018年4月30日
 *
 */
@Configuration
public class ShiroConfiguration {
    /**
     * LifecycleBeanPostProcessor,这是个DestructionAwareBeanPostProcessor的子类,
     * 负责org.apache.shiro.util.Initializable类型bean的生命周期的,初始化和销毁。
     * 主要是AuthorizingRealm类的子类,以及EhCacheManager类。
     */
    @Bean(name = "lifecycleBeanPostProcessor")
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * HashedCredentialsMatcher,这个类是为了对密码进行编码的,
     * 防止密码在数据库里明码保存,当然在登陆认证的时候,
     * 这个类也负责对form里输入的密码进行编码。
     */
    @Bean(name = "hashedCredentialsMatcher")
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(1024);
        credentialsMatcher.setStoredCredentialsHexEncoded(true);
        return credentialsMatcher;
    }

    /**ShiroRealm,这是个自定义的认证类,继承自AuthorizingRealm,
     * 负责用户的认证和权限的处理,可以参考JdbcRealm的实现。
     */
    @Bean(name = "shiroRealm")
    @DependsOn("lifecycleBeanPostProcessor")
    public PermissionsShiroRealm shiroRealm() {
    	PermissionsShiroRealm realm = new PermissionsShiroRealm();//这个类需要自己编写 下面会贴出其实现
        realm.setCredentialsMatcher(hashedCredentialsMatcher());
        return realm;
    }

    /**
     * EhCacheManager,缓存管理,用户登陆成功后,把用户信息和权限信息缓存起来,
     * 然后每次用户请求时,放入用户的session中,如果不设置这个bean,每个请求都会查询一次数据库。
     */
//    @Bean(name = "ehCacheManager")
//    @DependsOn("lifecycleBeanPostProcessor")
//    public EhCacheManager getEhCacheManager(){  
//        EhCacheManager ehcacheManager = new EhCacheManager();  
//        ehcacheManager.setCacheManagerConfigFile("classpath:ehcache.xml");  
//        return ehcacheManager;  
//    }  

    /**
     * SecurityManager,权限管理,这个类组合了登陆,登出,权限,session的处理,是个比较重要的类。
//     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(PermissionsShiroRealm shiroRealm ,SessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(shiroRealm);
//        securityManager.setCacheManager(getEhCacheManager());
        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    /**
     * ShiroFilterFactoryBean,是个factorybean,为了生成ShiroFilter。
     * 它主要保持了三项数据,securityManager,filters,filterChainDefinitionManager。
     */
    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(org.apache.shiro.mgt.SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);

//        Map<String, Filter> filters = new LinkedHashMap<>();
//        LogoutFilter logoutFilter = new LogoutFilter();
//        logoutFilter.setRedirectUrl("/api/1.0/loginout");
//        filters.put("logout",null);
//        shiroFilterFactoryBean.setFilters(filters);
        Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>();
        filterChainDefinitionManager.put("/api/1.0/logout", "logout");//登出URL
        filterChainDefinitionManager.put("/api/1.0/login", "anon");//登陆URL
        filterChainDefinitionManager.put("/api/1.0/nologin", "anon");//未登录跳转的URL
//      filterChainDefinitionManager.put("/user/edit/**", "authc,perms[user:edit]");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取,此处是用权限控制
        filterChainDefinitionManager.put("/**", "user");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
        shiroFilterFactoryBean.setLoginUrl("/api/1.0/nologin");
        
//        shiroFilterFactoryBean.setUnauthorizedUrl("/api/1.0/unauth");
        return shiroFilterFactoryBean;
    }

    /**
     * DefaultAdvisorAutoProxyCreator,Spring的一个bean,由Advisor决定对哪些类的方法进行AOP代理。
     */
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
        defaultAAP.setProxyTargetClass(true);
        return defaultAAP;
    }

    /**
     * AuthorizationAttributeSourceAdvisor,shiro里实现的Advisor类,
     * 内部使用AopAllianceAnnotationsAuthorizingMethodInterceptor来拦截用以下注解的方法。
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(org.apache.shiro.mgt.SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor aASA = new AuthorizationAttributeSourceAdvisor();
        aASA.setSecurityManager(securityManager);
        return aASA;
    }
    
    @Bean  
    public DefaultWebSessionManager configWebSessionManager(RedisSessionDao sessionDao) {  
		MySessionManager manager = new MySessionManager();  
		manager.setSessionDAO(sessionDao);// 设置SessionDao  
		manager.setDeleteInvalidSessions(true);// 删除过期的session  
		manager.setSessionValidationSchedulerEnabled(false);// 是否定时检查session 
        return manager;
    }
    
    
    public RedisSessionDao configRedisSessionDao() {
    	return new RedisSessionDao() ;
    }


}

  

猜你喜欢

转载自www.cnblogs.com/wuzhenzhao/p/9155576.html