Springboot_Shiro_redis集成

導(dǎo)入依賴(lài):

<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("開(kāi)始加載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");
        }
    }

理論來(lái)源可以參考:http://www.cnblogs.com/learnhow/p/5694876.html

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,119評(píng)論 25 709
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,410評(píng)論 4 61
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,596評(píng)論 19 139
  • 今天我滿懷感激。。。分享生命中的“和平”! 我與過(guò)去的一切,滿懷感激。雖然我感恩過(guò)挫折,但此刻,我更加感謝所有磨難...
    tiffany輝閱讀 165評(píng)論 0 1
  • 偏愛(ài),這些天腦海中常常出現(xiàn)這個(gè)詞,很奇怪,已經(jīng)持續(xù)很長(zhǎng)時(shí)間了。我不能對(duì)這個(gè)詞做出一個(gè)合理的詞語(yǔ)解釋?zhuān)Z(yǔ)文老師...
    迷失的星辰閱讀 2,386評(píng)論 2 0

友情鏈接更多精彩內(nèi)容