欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot+shiro+redis权限管理

程序员文章站 2022-04-30 21:22:19
...

1.pom.xml

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>1.6.0</version>
        </dependency>
        <!-- shiro+redis缓存插件 -->
        <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>2.4.2.1-RELEASE</version>
        </dependency>

2.shiro配置类

@Slf4j
@Configuration
public class ShiroConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.port}")
    private String port;

    @Value("${spring.redis.timeout}")
    private String timeout;

    @Value("${spring.redis.database}")
    private String database;

    @Autowired
    private RoleService roleService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置 SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // setLoginUrl 如果不设置值,默认会自动寻找Web工程根目录下的"/login.jsp"页面 或 "/login" 映射
        shiroFilterFactoryBean.setLoginUrl("/notLogin");
        // 设置无权限时跳转的 url;
        shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");

        Map<String, Filter> filtersMap = new LinkedHashMap<>();
        //可以配置RoleOrFilter的Bean
        filtersMap.put("roleOrFilter",new RolesOrFilterAuthorizationFilter());

        filtersMap.put("kickout",kickoutSessionControlFilter());


        shiroFilterFactoryBean.setFilters(filtersMap);
        // 设置拦截器
        Map<String, String> filterChainDefinitionMap = ShiroUtil.getFilterChainDefinitionMap(roleService);

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        log.info("Shiro拦截器工厂类注入成功");
        return shiroFilterFactoryBean;
    }
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm.
        securityManager.setRealm(shiroRealm());
        // 自定义缓存实现 使用redis
        securityManager.setCacheManager(cacheManager());
        // 自定义session管理 使用redis
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    /**
     * 身份认证realm; (这个需要自己写,账号密码校验;权限等)
     *
     * @return
     */
    @Bean
    public RealmConfig shiroRealm() {
        RealmConfig realmConfig = new RealmConfig();
        realmConfig.setCredentialsMatcher(hashedCredentialsMatcher());
        return realmConfig;
    }

    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        RetryLimitHashedCredentialsMatcher hct = new RetryLimitHashedCredentialsMatcher();
       /* // 加密算法的名称
        hct.setHashAlgorithmName("md5");
        // 配置加密的次数
        hct.setHashIterations(2);
        // 是否存储为16进制
        hct.setStoredCredentialsHexEncoded(true);*/
        return hct;
    }


    /**
     * cacheManager 缓存 redis实现
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     *
     * @return
     */
    public RedisManager redisManager() {
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(host);
        redisManager.setPort(Integer.parseInt(port));
        // 配置缓存过期时间  毫秒为单位
        redisManager.setExpire(Integer.parseInt(timeout));
        redisManager.setTimeout(Integer.parseInt(timeout));
        redisManager.setPassword(password);
        return redisManager;
    }

    /**
     * Session Manager
     * 使用的是shiro-redis开源插件
     */
    @Bean
    public DefaultWebSessionManager sessionManager() {
        SessionConfig sessionManager = new SessionConfig();
        sessionManager.setSessionDAO(redisSessionDAO());
        return sessionManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao层的实现 通过redis
     * 使用的是shiro-redis开源插件
     */
    @Bean
    public EnterpriseCacheSessionDAO redisSessionDAO() {
        SessionDaoConfig sessionDaoConfig=new SessionDaoConfig();
        sessionDaoConfig.setRedisManager(redisManager());
        sessionDaoConfig.setSessionIdGenerator(new UuidSessionIdGenerator());
        return sessionDaoConfig;
    }

    /**
     * 限制同一账号登录同时登录人数控制
     *
     * @return
     */
    @Bean
    public KickoutSessionControlFilter kickoutSessionControlFilter() {
        KickoutSessionControlFilter kickoutSessionControlFilter = new KickoutSessionControlFilter();
        kickoutSessionControlFilter.setCacheManager(cacheManager());
        kickoutSessionControlFilter.setSessionManager(sessionManager());
        kickoutSessionControlFilter.setKickoutAfter(false);
        kickoutSessionControlFilter.setMaxSession(1);
        kickoutSessionControlFilter.setKickoutUrl("/kickout");
        return kickoutSessionControlFilter;
    }


    /***
     * 授权所用配置
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }

    /***
     * 使授权注解起作用不如不想配置可以在pom文件中加入
     * <dependency>
     *<groupId>org.springframework.boot</groupId>
     *<artifactId>spring-boot-starter-aop</artifactId>
     *</dependency>
     * @param securityManager
     * @return
     */
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }

    /**
     * Shiro生命周期处理器
     *
     */
    @Bean
    public static LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

}

2.认证和授权 

@Slf4j
public class RealmConfig extends AuthorizingRealm {
    //如果项目中用到了事物,@Autowired注解会使事物失效,可以自己用get方法获取值

    @Autowired
    @Lazy
    private com.ccp.provider.auth.service.UserService userService;

    @Autowired
    @Lazy
    private com.ccp.provider.customer.service.UserService customerService;

    @Autowired
    @Lazy
    private WriteOffUserService writOffUserService;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 授权
     */

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        logger.info("---------------- 执行 Shiro 权限获取 ---------------------");
        Object principal = principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if (principal instanceof SysUser) {
            SysUser userLogin = (SysUser) principal;
            Set<String> roles = roleService.findRoleNameByUserId(userLogin.getId());
            authorizationInfo.addRoles(roles);

            Set<String> permissions = userService.findPermissionsByUserId(userLogin.getId());
            authorizationInfo.addStringPermissions(permissions);
        }
        logger.info("---- 获取到以下权限 ----");
        logger.info(authorizationInfo.getStringPermissions().toString());
        logger.info("---------------- Shiro 权限获取成功 ----------------------");
        return authorizationInfo;
    }

   
    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authctoken) throws AuthenticationException {
        logger.info("---------------- 执行 Shiro 凭证认证 ----------------------");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String name = token.getUsername();
        String password = String.valueOf(token.getPassword());
        SysUser user = new SysUser();
        user.setUserName(name);
        user.setPassWord(password);
        // 从数据库获取对应用户名密码的用户
        SysUser userList = userService.getUser(user);
        if (userList != null) {
            // 用户为禁用状态
            if (userList.getUserEnable() != 1) {
                throw new DisabledAccountException();
            }
            logger.info("---------------- Shiro 凭证认证成功 ----------------------");
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    userList, //用户
                    userList.getPassWord(), //密码
                    getName()  //realm name
            );
            return authenticationInfo;
        }
        throw new UnknownAccountException();
    }

    

    /**
     * 清空已经放入缓存的授权信息。
     * */
    public void clearCache() {
        PrincipalCollection principals=SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}

3.密码校验

public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher{


    /**
     *  验证密码
     * @param token
     * @param info
     * @return
     */
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
            //如果是免密登录直接返回true
            if(tk.getType().equals(LoginType.NOPASSWD)){
                  return true;
            }
             //不是免密登录,调用父类的方法
            return super.doCredentialsMatch(tk, info);
    }
}

4.刷新权限

/**
 * @Title: ShiroUtil
 * @Description: shiro工具类
 * @Author <a href="mailto:[email protected]">陈晓博</a>
 * @Date 2019-05-23 15:37
 * @Version V1.0
 */
public class ShiroUtil {

    public static Map<String, String> getFilterChainDefinitionMap(RoleService roleService){
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        List<Permission> list = roleService.selectPermissionAll();

        filterChainDefinitionMap.put("/loginTest", "anon");
        filterChainDefinitionMap.put("/logoutTest", "anon");
        filterChainDefinitionMap.put("/excel", "anon");
        filterChainDefinitionMap.put("/druid/**", "anon");
        filterChainDefinitionMap.put("/h5decoration/detail", "anon");



        List<String> excludePathPatterns=WebMvcConfig.getExcludePathPatterns();
        for(String string:excludePathPatterns){
            filterChainDefinitionMap.put(string, "anon");

        }

        //主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截
        for(Permission filter : list){
            filterChainDefinitionMap.put(filter.getHref()+"/**","roleOrFilter["+(filter.getRoles()==null?"":filter.getRoles())+"]");
        }
        filterChainDefinitionMap.put("/**", "authc");
        return filterChainDefinitionMap;
    }


    /**
     * 重新赋值权限(在比如:给一个角色临时添加一个权限,需要调用此方法刷新权限,否则还是没有刚赋值的权限)
     * @param myRealm 自定义的realm
     * @param token 用户登录信息
     */
    public static void reloadAuthorizing(RealmConfig myRealm,LoginToken token){
        Subject subject = SecurityUtils.getSubject();
        String realmName = subject.getPrincipals().getRealmNames().iterator().next();
        //第一个参数为用户名,第二个参数为realmName,test想要操作权限的用户
        SimplePrincipalCollection principals = new SimplePrincipalCollection(token,realmName);
        subject.runAs(principals);
        subject.releaseRunAs();
    }

    /**
     * @title 刷新用户权限
     * @desc principal为用户的认证信息
     */
    public static void  reloadAuthorizing() throws Exception{
        Subject subject = SecurityUtils.getSubject();
        LoginToken principal=(LoginToken) subject.getPrincipal();
        RealmSecurityManager rsm = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        RealmConfig myShiroRealm = (RealmConfig) rsm.getRealms().iterator().next();
        String realmName="";
        if(subject.getPrincipals() !=null && subject.getPrincipals().getRealmNames() !=null && subject.getPrincipals().getRealmNames().iterator() != null){
            realmName = subject.getPrincipals().getRealmNames().iterator().next();
        }
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, realmName);
        subject.runAs(principals);
        if(myShiroRealm.isAuthenticationCachingEnabled()) {
            myShiroRealm.getAuthenticationCache().remove(principals);
        }
        if(myShiroRealm.isAuthorizationCachingEnabled()) {
            // 删除指定用户shiro权限
            myShiroRealm.getAuthorizationCache().remove(principals);
        }
        myShiroRealm.clearCache();
        // 刷新权限
        subject.releaseRunAs();

    }

}

 

相关标签: springboot 集成