前言
創(chuàng)新互聯(lián)建站專注于云縣企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),商城系統(tǒng)網(wǎng)站開發(fā)。云縣網(wǎng)站建設(shè)公司,為云縣等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站制作,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)建站專業(yè)和態(tài)度為您提供的服務(wù)
shiro是一個(gè)權(quán)限框架,具體的使用可以查看其官網(wǎng) http://shiro.apache.org/ 它提供了很方便的權(quán)限認(rèn)證和登錄的功能.
而springboot作為一個(gè)開源框架,必然提供了和shiro整合的功能!
之前項(xiàng)目鑒權(quán)一直使用的Shiro,那是在Spring MVC里面使用的比較多,而且都是用XML來(lái)配置,用Shiro來(lái)做權(quán)限控制相對(duì)比較簡(jiǎn)單而且成熟,而且我一直都把Shiro的session放在MongoDB中,這個(gè)比較符合mongodb的設(shè)計(jì)初衷,而且在分布式項(xiàng)目中mongodb也作為一個(gè)中間層,用來(lái)很好很方便解決分布式環(huán)境下的session同步的問(wèn)題
自從SpringBoot問(wèn)世之后我的項(xiàng)目基本上能用SpringBoot的就會(huì)用SpringBoot,用MAVEN做統(tǒng)一集中管理也很方便,雖然SpringBoot也提供了一套權(quán)限安全框架Spring Security,但是相對(duì)來(lái)說(shuō)還是不是太好用,所以還是用Shiro來(lái)的方便一點(diǎn),SpringBoot集成Shiro要比Spring MVC要簡(jiǎn)單的多,至少?zèng)]有一堆XML配置,看起來(lái)更清爽,那么接下來(lái)我們就開始集成。
方法如下:
第一步必然是在MAVEN中先添加Shiro和mongo的依賴,我用的Shiro版本是
<shiro.version>1.2.3</shiro.version>
添加依賴:
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.7.0.RELEASE</version> </dependency>
然后在application.xml或yml中配置mongodb
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.port=27017 spring.data.mongodb.database=SHIRO_INFO
配置完成之后我們開始正式寫Shiro認(rèn)證的代碼,先自定義一個(gè)鑒權(quán)realm,繼承自AuthorizingRealm
public class ShiroDbRealm extends AuthorizingRealm { /** * 用戶信息操作 */ private SystemUserService systemUserService; public ShiroDbRealm() {} public ShiroDbRealm(SystemUserService systemUserService) { this.systemUserService = systemUserService; } /** * 授權(quán)信息 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { SimpleAuthorizationInfo info = (SimpleAuthorizationInfo) ShiroKit.getShiroSessionAttr("perms"); if (null != info && !CollectionUtils.isEmpty(info.getRoles()) && !CollectionUtils.isEmpty(info.getStringPermissions())) { return info; } return null; } /** * 認(rèn)證信息 */ protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authcToken; String userName = token.getUsername(); if (userName != null && !"".equals(userName)) { SystemUser key = new SystemUser(); key.setLoginName(token.getUsername()); key.setPassword(String.valueOf(token.getPassword())); SystemUser user = systemUserService.login(key); if (user != null) { Subject userTemp = SecurityUtils.getSubject(); userTemp.getSession().setAttribute("userId", user.getId()); userTemp.getSession().setAttribute("userName", user.getUserName()); return new SimpleAuthenticationInfo(user.getLoginName(), user.getPassword(), getName()); } } return null; } }
存儲(chǔ)session進(jìn)mongodb的Repository和實(shí)現(xiàn):
public interface ShiroSessionRepository { /** * * @param session */ void saveSession(Session session); ...... }
MongoDBSessionRepository.java
public class MongoDBSessionRepository implements ShiroSessionRepository { private MongoTemplate mongoTemplate; public MongoDBSessionRepository() {} public MongoDBSessionRepository(MongoTemplate mongoTemplate) { this.mongoTemplate = mongoTemplate; } @Override public void saveSession(Session session) { if (session == null || session.getId() == null) { return; } SessionBean bean = new SessionBean(); bean.setKey(getSessionKey(session.getId())); bean.setValue(SerializeUtil.serialize(session)); bean.setPrincipal(null); bean.setHost(session.getHost()); bean.setStartTimestamp(session.getStartTimestamp()); bean.setLastAccessTime(session.getLastAccessTime()); bean.setTimeoutTime(getTimeoutTime(session.getStartTimestamp(), session.getTimeout())); mongoTemplate.insert(bean); } ...... }
ShiroSessionDAO.java
public class ShiroSessionDAO extends AbstractSessionDAO { /** * 日志記錄器 */ private static final Logger log = LoggerFactory.getLogger(ShiroSessionDAO.class); /** * 數(shù)據(jù)庫(kù)存儲(chǔ) */ private ShiroSessionRepository shiroSessionRepository; /** * * @return */ public ShiroSessionRepository getShiroSessionRepository() { return shiroSessionRepository; } /** * * @param shiroSessionRepository */ public void setShiroSessionRepository(ShiroSessionRepository shiroSessionRepository) { this.shiroSessionRepository = shiroSessionRepository; } @Override public void update(Session session) throws UnknownSessionException { getShiroSessionRepository().updateSession(session); } @Override public void delete(Session session) { if (session == null) { log.error("session can not be null,delete failed"); return; } Serializable id = session.getId(); if (id != null) { getShiroSessionRepository().deleteSession(id); } } @Override public Collection<Session> getActiveSessions() { return getShiroSessionRepository().getAllSessions(); } @Override protected Serializable doCreate(Session session) { Serializable sessionId = this.generateSessionId(session); this.assignSessionId(session, sessionId); getShiroSessionRepository().saveSession(session); return sessionId; } @Override protected Session doReadSession(Serializable sessionId) { return getShiroSessionRepository().getSession(sessionId); } }
OK!所有基礎(chǔ)類已經(jīng)完成,最后寫一個(gè)config用來(lái)全部初始化和配置Shiro
@Configuration public class ShiroConfig { @Resource private MongoTemplate mongoTemplate; @Resource private SystemUserService systemUserService;// 這是用來(lái)判斷用戶名和密碼的service @Bean public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) { ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); shiroFilterFactoryBean.setLoginUrl("/login"); shiroFilterFactoryBean.setSuccessUrl("/index"); shiroFilterFactoryBean.setUnauthorizedUrl("/403"); // 攔截器. Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/ajaxLogin", "anon"); filterChainDefinitionMap.put("/libs/**", "anon"); filterChainDefinitionMap.put("/images/**", "anon"); filterChainDefinitionMap.put("/logout", "logout"); filterChainDefinitionMap.put("/**", "authc"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( DefaultWebSecurityManager securityManager) { AuthorizationAttributeSourceAdvisor adv = new AuthorizationAttributeSourceAdvisor(); adv.setSecurityManager(securityManager); return adv; } @Bean public DefaultWebSecurityManager securityManager(DefaultWebSessionManager sessionManager, ShiroDbRealm myShiroRealm) { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); // 設(shè)置realm. securityManager.setRealm(myShiroRealm); securityManager.setSessionManager(sessionManager); return securityManager; } /** * 身份認(rèn)證realm; (這里傳遞systemUserService給自定義的ShiroDbRealm初始化) * * @return */ @Bean public ShiroDbRealm myShiroRealm() { ShiroDbRealm myShiroRealm = new ShiroDbRealm(systemUserService); return myShiroRealm; } @Bean public DefaultWebSessionManager sessionManager(ShiroSessionDAO shiroSessionDao) { DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); sessionManager.setGlobalSessionTimeout(1800000l); sessionManager.setDeleteInvalidSessions(true); sessionManager.setSessionValidationSchedulerEnabled(true); sessionManager.setSessionDAO(shiroSessionDao); sessionManager.setSessionIdCookieEnabled(true); SimpleCookie cookie = new SimpleCookie(ShiroHttpSession.DEFAULT_SESSION_ID_NAME); cookie.setHttpOnly(true); cookie.setMaxAge(1800000); sessionManager.setSessionIdCookie(cookie); return sessionManager; } @Bean public ShiroSessionDAO shiroSessionDao(MongoDBSessionRepository shiroSessionRepository) { ShiroSessionDAO dao = new ShiroSessionDAO(); dao.setShiroSessionRepository(shiroSessionRepository); return dao; } @Bean MongoDBSessionRepository shiroSessionRepository() { MongoDBSessionRepository resp = new MongoDBSessionRepository(mongoTemplate); return resp; } }
大功告成,這里只是一個(gè)簡(jiǎn)單的配置,代碼也是我從項(xiàng)目里面節(jié)選和修改過(guò)的,至于在controller里面怎么使用,怎么做不同權(quán)限的鑒權(quán)工作那就在自己的代碼里面實(shí)現(xiàn)就行。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)創(chuàng)新互聯(lián)的支持。
分享名稱:SpringBoot集成Shiro并利用MongoDB做Session存儲(chǔ)的方法詳解
分享路徑:http://aaarwkj.com/article14/igeoge.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、網(wǎng)站收錄、品牌網(wǎng)站設(shè)計(jì)、企業(yè)網(wǎng)站制作、虛擬主機(jī)、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)