轉載至:https://blog.csdn.net/u013615903/article/details/78781166
項目背景
公司在幾年前就采用了前后端分離的開發模式,前端所有請求都使用ajax。這樣的項目結構在與CAS單點登錄等權限管理框架集成時遇到了很多問題,使得權限部分的代碼冗長丑陋,CAS的各種重定向也使得用戶體驗很差,在前端使用vue-router管理頁面跳轉時,問題更加尖銳。於是我就在尋找一個解決方案,這個方案應該對代碼的侵入較少,開發速度快,實現優雅。最近無意中看到springboot與shiro框架集成的文章,在了解了springboot以及shiro的發展狀況,並學習了使用方法后,開始在網上搜索前后端分離模式下這兩個框架的適應性,在經過測試后發現可行,完全符合個人預期。
解決方案
本文中項目核心包為SpringBoot1.5.9.RELEASE以及shiro-spring 1.4.0,為了加快開發效率,持久化框架使用hibernate-JPA,為增加可靠性,sessionId的管理使用了shiro-redis開源插件,避免sessionId斷電丟失,同時使得多端可共享session,項目結構為多模塊項目,詳見下圖。

其中spring-boot-shiro模塊為本文重點,該模塊包含shiro核心配置,shiro數據源配置以及各種自定義實現,登錄相關服務等。該模塊在項目中使用時可直接在pom中引用,並在spring-boot-main入口模塊中配置相應數據庫連接信息即可,且該模塊可以在多個項目中復用,避免重復開發。spring-boot-module1為模擬真實項目中的業務模塊,可能會有多個。spring-boot-common中包含通用工具類,常量,異常等等。多模塊項目的搭建在本文中不作贅述。
母模塊pom.xml代碼如下
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.xxx</groupId> <artifactId>spring-boot-parent</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>spring-boot-main</module> <module>spring-boot-module1</module> <module>spring-boot-shiro</module> <module>spring-boot-common</module> </modules> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-boot.version>1.5.9.RELEASE</spring-boot.version> <shiro.version>1.4.0</shiro.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${spring-boot.version}</version> </dependency> <!--在外部tomcat中發布故移除內置包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>${spring-boot.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <version>${spring-boot.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <version>${spring-boot.version}</version> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>${spring-boot.version}</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>${shiro.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.8</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.28</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.39</version> <scope>runtime</scope> </dependency> <!--<dependency>--> <!--<groupId>org.springframework.boot</groupId>--> <!--<artifactId>spring-boot-starter-thymeleaf</artifactId>--> <!--<version>${spring-boot.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>net.sourceforge.nekohtml</groupId>--> <!--<artifactId>nekohtml</artifactId>--> <!--<version>1.9.22</version>--> <!--</dependency>--> </dependencies> </project>
spring-boot-shiro模塊接口如下圖

傳統結構項目中,shiro從cookie中讀取sessionId以此來維持會話,在前后端分離的項目中(也可在移動APP項目使用),我們選擇在ajax的請求頭中傳遞sessionId,因此需要重寫shiro獲取sessionId的方式。自定義MySessionManager類繼承DefaultWebSessionManager類,重寫getSessionId方法,代碼如下
import org.apache.shiro.web.servlet.ShiroHttpServletRequest; import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; import org.apache.shiro.web.util.WebUtils; import org.springframework.util.StringUtils; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.Serializable; /** * Created by Administrator on 2017/12/11. * 自定義sessionId獲取 */ public class MySessionManager extends DefaultWebSessionManager { private static final String AUTHORIZATION = "Authorization"; private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request"; public MySessionManager() { super(); } @Override protected Serializable getSessionId(ServletRequest request, ServletResponse response) { String id = WebUtils.toHttp(request).getHeader(AUTHORIZATION); //如果請求頭中有 Authorization 則其值為sessionId if (!StringUtils.isEmpty(id)) { request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id); request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE); return id; } else { //否則按默認規則從cookie取sessionId return super.getSessionId(request, response); } } }
如何配置讓shiro執行我們的自定義sessionManager呢?下面看ShiroConfig類。
package com.xxx.shiro.config; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.mgt.SessionManager; import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.crazycake.shiro.RedisCacheManager; import org.crazycake.shiro.RedisManager; import org.crazycake.shiro.RedisSessionDAO; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerExceptionResolver; import java.util.LinkedHashMap; import java.util.Map; /** * Created by Administrator on 2017/12/11. */ @Configuration public class ShiroConfig { @Value("${spring.redis.shiro.host}") private String host; @Value("${spring.redis.shiro.port}") private int port; @Value("${spring.redis.shiro.timeout}") private int timeout; @Value("${spring.redis.shiro.password}") private String password; @Bean public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { System.out.println("ShiroConfiguration.shirFilter()"); ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); shiroFilterFactoryBean.setSecurityManager(securityManager); Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>(); //????????? ???? //???? ???,??????????Shiro?????????????????loginUrl filterChainDefinitionMap.put("/logout", "logout"); // ?????????? ???? filterChainDefinitionMap.put("/static/**", "anon"); filterChainDefinitionMap.put("/ajaxLogin", "anon"); filterChainDefinitionMap.put("/login", "anon"); filterChainDefinitionMap.put("/**", "authc"); //??shiro???????????????????????????????????json?? shiroFilterFactoryBean.setLoginUrl("/unauth"); // ??????????? // shiroFilterFactoryBean.setSuccessUrl("/index"); //?????; // shiroFilterFactoryBean.setUnauthorizedUrl("/403"); shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap); return shiroFilterFactoryBean; } /** * ????? * ????????????Shiro?SimpleAuthenticationInfo????? * ? * * @return */ @Bean public HashedCredentialsMatcher hashedCredentialsMatcher() { HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher(); hashedCredentialsMatcher.setHashAlgorithmName("md5"); //????:????MD5??; hashedCredentialsMatcher.setHashIterations(2); //???????????????? md5(md5("")); return hashedCredentialsMatcher; } @Bean public MyShiroRealm myShiroRealm() { MyShiroRealm myShiroRealm = new MyShiroRealm(); myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher()); return myShiroRealm; } @Bean public SecurityManager securityManager() { DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(myShiroRealm()); // ???session?? ??redis securityManager.setSessionManager(sessionManager()); // ??????? ??redis securityManager.setCacheManager(cacheManager()); return securityManager; } //???sessionManager @Bean public SessionManager sessionManager() { MySessionManager mySessionManager = new MySessionManager(); mySessionManager.setSessionDAO(redisSessionDAO()); return mySessionManager; } /** * ??shiro redisManager * <p> * ????shiro-redis???? * * @return */ public RedisManager redisManager() { RedisManager redisManager = new RedisManager(); redisManager.setHost(host); redisManager.setPort(port); redisManager.setExpire(1800); // ???????? redisManager.setTimeout(timeout); redisManager.setPassword(password); return redisManager; } /** * cacheManager ?? redis?? * <p> * ????shiro-redis???? * * @return */ @Bean public RedisCacheManager cacheManager() { RedisCacheManager redisCacheManager = new RedisCacheManager(); redisCacheManager.setRedisManager(redisManager()); return redisCacheManager; } /** * RedisSessionDAO shiro sessionDao???? ??redis * <p> * ????shiro-redis???? */ @Bean public RedisSessionDAO redisSessionDAO() { RedisSessionDAO redisSessionDAO = new RedisSessionDAO(); redisSessionDAO.setRedisManager(redisManager()); return redisSessionDAO; } /** * ??shiro aop????. * ??????;??????????; * * @param securityManager * @return */ @Bean public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor( SecurityManager securityManager) { AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); return authorizationAttributeSourceAdvisor; } /** * ???????? * @return */ @Bean(name = "exceptionHandler") public HandlerExceptionResolver handlerExceptionResolver() { return new MyExceptionHandler(); } }
在定義的SessionManager的Bean中返回我們的MySessionManager,然后在SecurityManager的Bean中調用setSessionManager(SessionManager sessionManager)方法加載我們的自定義SessionManager。
附上
MyShiroRealm的代碼
package com.xxx.shiro.config; import com.xxx.shiro.entity.SysPermission; import com.xxx.shiro.entity.SysRole; import com.xxx.shiro.entity.UserInfo; import com.xxx.shiro.service.UserInfoService; import org.apache.shiro.authc.*; 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.util.ByteSource; import javax.annotation.Resource; /** * Created by Administrator on 2017/12/11. * 自定義權限匹配和賬號密碼匹配 */ public class MyShiroRealm extends AuthorizingRealm { @Resource private UserInfoService userInfoService; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { // System.out.println("權限配置-->MyShiroRealm.doGetAuthorizationInfo()"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); UserInfo userInfo = (UserInfo) principals.getPrimaryPrincipal(); for (SysRole role : userInfo.getRoleList()) { authorizationInfo.addRole(role.getRole()); for (SysPermission p : role.getPermissions()) { authorizationInfo.addStringPermission(p.getPermission()); } } return authorizationInfo; } /*主要是用來進行身份認證的,也就是說驗證用戶輸入的賬號和密碼是否正確。*/ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // System.out.println("MyShiroRealm.doGetAuthenticationInfo()"); //獲取用戶的輸入的賬號. String username = (String) token.getPrincipal(); // System.out.println(token.getCredentials()); //通過username從數據庫中查找 User對象,如果找到,沒找到. //實際項目中,這里可以根據實際情況做緩存,如果不做,Shiro自己也是有時間間隔機制,2分鍾內不會重復執行該方法 UserInfo userInfo = userInfoService.findByUsername(username); // System.out.println("----->>userInfo="+userInfo); if (userInfo == null) { return null; } if (userInfo.getState() == 1) { //賬戶凍結 throw new LockedAccountException(); } SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo( userInfo, //用戶名 userInfo.getPassword(), //密碼 ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt getName() //realm name ); return authenticationInfo; } }
傳統項目中,登錄成功后應該重定向請求,但在前后端分離項目中,通過ajax登錄后應該返回登錄狀態標志以及相關信息。Web層登錄方法代碼如下
/** * 登錄方法 * @param userInfo * @return */ @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST) @ResponseBody public String ajaxLogin(UserInfo userInfo) { JSONObject jsonObject = new JSONObject(); Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword()); try { subject.login(token); jsonObject.put("token", subject.getSession().getId()); jsonObject.put("msg", "登錄成功"); } catch (IncorrectCredentialsException e) { jsonObject.put("msg", "密碼錯誤"); } catch (LockedAccountException e) { jsonObject.put("msg", "登錄失敗,該用戶已被凍結"); } catch (AuthenticationException e) { jsonObject.put("msg", "該用戶不存在"); } catch (Exception e) { e.printStackTrace(); } return jsonObject.toString(); }
本項目使用SpringMVC框架,可以自行修改使用其他MVC框架。登錄成功則返回sessionId作為token給前端存儲,前端請求時將該token放入請求頭,以Authorization為key,以此來鑒權。如果出現賬號或密碼錯誤等異常則返回錯誤信息。
傳統項目中,登出后應重定向請求,到登錄界面或其他指定界面,在前后端分離的項目中,我們應該返回json信息。在上面提到的ShiroConfig中配置了默認登錄路由

在Web層加入方法
/** * 未登錄,shiro應重定向到登錄界面,此處返回未登錄狀態信息由前端控制跳轉頁面 * @return */ @RequestMapping(value = "/unauth") @ResponseBody public Object unauth() { Map<String, Object> map = new HashMap<String, Object>(); map.put("code", "1000000"); map.put("msg", "未登錄"); return map; }
此處簡單提示未登錄返回狀態碼,也可自行定義信息。
在項目中,權限相關表可能不在業務庫中,因此有必要單獨配置權限相關表的數據源。詳細配置可以參見《Spring Boot多數據源配置與使用》一文。
Shiro數據源配置代碼
package com.xxx.shiro.datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
/**
* Created by Administrator on 2017/12/11.
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "shiroEntityManagerFactory", transactionManagerRef = "shiroTransactionManager", basePackages = {
"com.xxx.shiro.dao"}
)
public class ShiroDataSourceConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("shiroDataSource")
private DataSource shiroDataSource;
@Bean(name = "shiroEntityManager")
public EntityManager shiroEntityManager(EntityManagerFactoryBuilder builder) {
return shiroEntityManagerFactory(builder).getObject()
.createEntityManager();
}
@Bean(name = "shiroEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean shiroEntityManagerFactory(
EntityManagerFactoryBuilder builder) {
return builder.dataSource(shiroDataSource)
.properties(getVendorProperties(shiroDataSource))
.packages("com.xxx.shiro.entity")
.persistenceUnit("shiroPersistenceUnit").build();
}
private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Bean(name = "shiroTransactionManager")
PlatformTransactionManager shiroTransactionManager(
EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(shiroEntityManagerFactory(builder)
.getObject());
}
}
IDEA下JpaProperties可能會報錯,可以忽略。
入口模塊結構如下圖

DataSourceConfig中配置了多個數據源的Bean,其中shiro數據源Bean代碼
/** * shiro數據源 * @return */ @Bean(name = "shiroDataSource") @Qualifier("shiroDataSource") @ConfigurationProperties(prefix="spring.datasource.shiro") public DataSource shiroDataSource() { return DataSourceBuilder.create().build(); } ServletInitializer和StartApp為SpringBoot在外部tomcat啟動配置,不贅述。 SpringBoot的相關配置在application.yml中,shiro配置代碼如下圖 Primary為主庫配置。當在某個項目中引入spring-boot-shiro模塊時,只需要在配置文件中加入shiro數據源及redis的相關配置,並在DataSourceConfig加入shiro數據源Bean即可。 Shiro框架會根據用戶登錄及權限狀態拋出異常,建議使用SpringMVC的全局異常捕獲來處理異常,避免重復代碼。該項目中代碼如下 package com.xxx.shiro.config; import com.alibaba.fastjson.support.spring.FastJsonJsonView; import org.apache.shiro.authz.UnauthenticatedException; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2017/12/11. * 全局異常處理 */ public class MyExceptionHandler implements HandlerExceptionResolver { public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) { ModelAndView mv = new ModelAndView(); FastJsonJsonView view = new FastJsonJsonView(); Map<String, Object> attributes = new HashMap<String, Object>(); if (ex instanceof UnauthenticatedException) { attributes.put("code", "1000001"); attributes.put("msg", "token錯誤"); } else if (ex instanceof UnauthorizedException) { attributes.put("code", "1000002"); attributes.put("msg", "用戶無權限"); } else { attributes.put("code", "1000003"); attributes.put("msg", ex.getMessage()); } view.setAttributesMap(attributes); mv.setView(view); return mv; } }
該Bean在ShiroConfig中已有注冊代碼。
至此,shiro框架的集成就結束了。至於shiro框架的使用細節,可以自行查閱相關資料。項目代碼本人測試可正常工作,未應用到生產環境,僅供學習交流使用。
---------------------
作者:ReWinD00
來源:CSDN
原文:https://blog.csdn.net/u013615903/article/details/78781166
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!
