Springboot_Shiro_redis集成

导入依赖:

<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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,526评论 25 709
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,294评论 4 61
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,253评论 19 139
  • 今天我满怀感激。。。分享生命中的“和平”! 我与过去的一切,满怀感激。虽然我感恩过挫折,但此刻,我更加感谢所有磨难...
    tiffany辉阅读 148评论 0 1
  • 偏爱,这些天脑海中常常出现这个词,很奇怪,已经持续很长时间了。我不能对这个词做出一个合理的词语解释,语文老师...
    迷失的星辰阅读 2,275评论 2 0