在先後端分離的SpringBoot項目中集成Shiro權限框架

項目背景

       公司在幾年前就採用了先後端分離的開發模式,前端全部請求都使用ajax。這樣的項目結構在與CAS單點登陸等權限管理框架集成時遇到了不少問題,使得權限部分的代碼冗長醜陋,CAS的各類重定向也使得用戶體驗不好,在前端使用vue-router管理頁面跳轉時,問題更加尖銳。因而我就在尋找一個解決方案,這個方案應該對代碼的侵入較少,開發速度快,實現優雅。最近無心中看到springboot與shiro框架集成的文章,在瞭解了springboot以及shiro的發展情況,並學習了使用方法後,開始在網上搜索先後端分離模式下這兩個框架的適應性,在通過測試後發現可行,徹底符合我的預期。html

解決方案

       本文中項目核心包爲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中包含通用工具類,常量,異常等等。多模塊項目的搭建在本文中不做贅述。vue


母模塊pom.xml代碼以下:java

<?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模塊接口以下圖mysql

       傳統結構項目中,shiro從cookie中讀取sessionId以此來維持會話,在先後端分離的項目中(也可在移動APP項目使用),咱們選擇在ajax的請求頭中傳遞sessionId,所以須要重寫shiro獲取sessionId的方式。自定義MySessionManager類繼承DefaultWebSessionManager類,重寫getSessionId方法,代碼以下   web

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類。ajax

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。redis


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層登陸方法代碼以下:spring

    /**
     * 登陸方法
     * @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;
    }

       此處簡單提示未登陸返回狀態碼,也可自行定義信息。

       Shiro數據源配置代碼

package com.xxx.shiro.datasource;
 
import java.util.Map;
import javax.persistence.EntityManager;
import javax.sql.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;
 
/**
 * 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框架的使用細節,能夠自行查閱相關資料。項目代碼本人測試可正常工做,未應用到生產環境,僅供學習交流使用。

相關文章
相關標籤/搜索