Springboot_Shiro_redis集成

導(dǎo)入依賴:

<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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末键菱,一起剝皮案震驚了整個濱河市笛辟,隨后出現(xiàn)的幾起案子趟脂,更是在濱河造成了極大的恐慌,老刑警劉巖砌烁,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)罪郊,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來尚洽,“玉大人悔橄,你說我怎么就攤上這事。” “怎么了癣疟?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵尺铣,是天一觀的道長。 經(jīng)常有香客問我争舞,道長凛忿,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任竞川,我火速辦了婚禮店溢,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘委乌。我一直安慰自己床牧,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布遭贸。 她就那樣靜靜地躺著戈咳,像睡著了一般。 火紅的嫁衣襯著肌膚如雪壕吹。 梳的紋絲不亂的頭發(fā)上著蛙,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天,我揣著相機(jī)與錄音耳贬,去河邊找鬼踏堡。 笑死,一個胖子當(dāng)著我的面吹牛咒劲,可吹牛的內(nèi)容都是我干的顷蟆。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼腐魂,長吁一口氣:“原來是場噩夢啊……” “哼帐偎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起蛔屹,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤削樊,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后判导,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體嫉父,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年眼刃,在試婚紗的時候發(fā)現(xiàn)自己被綠了绕辖。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡擂红,死狀恐怖仪际,靈堂內(nèi)的尸體忽然破棺而出围小,到底是詐尸還是另有隱情,我是刑警寧澤树碱,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布肯适,位于F島的核電站,受9級特大地震影響成榜,放射性物質(zhì)發(fā)生泄漏框舔。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一赎婚、第九天 我趴在偏房一處隱蔽的房頂上張望刘绣。 院中可真熱鬧,春花似錦挣输、人聲如沸纬凤。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽停士。三九已至,卻和暖如春完丽,著一層夾襖步出監(jiān)牢的瞬間恋技,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工舰涌, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留猖任,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓瓷耙,卻偏偏與公主長得像,于是被迫代替她去往敵國和親刁赖。 傳聞我的和親對象是個殘疾皇子搁痛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,304評論 25 707
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件宇弛、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,121評論 4 61
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理鸡典,服務(wù)發(fā)現(xiàn),斷路器枪芒,智...
    卡卡羅2017閱讀 134,707評論 18 139
  • 今天我滿懷感激彻况。。舅踪。分享生命中的“和平”纽甘! 我與過去的一切,滿懷感激抽碌。雖然我感恩過挫折悍赢,但此刻,我更加感謝所有磨難...
    tiffany輝閱讀 143評論 0 1
  • 偏愛,這些天腦海中常常出現(xiàn)這個詞左权,很奇怪皮胡,已經(jīng)持續(xù)很長時間了。我不能對這個詞做出一個合理的詞語解釋赏迟,語文老師...
    迷失的星辰閱讀 2,215評論 2 0