1. 程式人生 > >SpringBoot整合Shiro自定義Redis存儲

SpringBoot整合Shiro自定義Redis存儲

min locked 訪問控制 ride ora efault protect contex lan

Shiro

  Shiro 主要分為 安全認證 和 接口授權 兩個部分,其中的核心組件為 Subject、 SecurityManager、 Realms,公共部分 Shiro 都已經為我們封裝好了,我們只需要按照一定的規則去編寫響應的代碼即可…

  Subject 表示主體,將用戶的概念理解為當前操作的主體,它即可以是一個通過瀏覽器請求的用戶,也可能是一個運行的程序,外部應用與 Subject 進行交互,記錄當前操作用戶。Subject 代表當前用戶的安全操作,SecurityManager 則管理所有用戶的安全操作。

  SecurityManager 即安全管理器,對所有的 Subject 進行安全管理,並通過它來提供安全管理的各種服務(認證、授權等)

  Realm 充當了應用與數據安全間的 橋梁 或 連接器。當對用戶執行認證(登錄)和授權(訪問控制)驗證時,Shiro 會從應用配置的 Realm 中查找用戶及其權限信息。

1.導入shiro依賴

技術分享圖片
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.4.0</version>
        </dependency>
    
     <!-- hiro-redis插件用於實現:將用戶信息交給redis管理 -->
        <dependency>
            <groupId>org.crazycake</groupId>
            <artifactId>shiro-redis</artifactId>
            <version>2.8.24</version>
        </dependency>
技術分享圖片

2.shiro配置類

技術分享圖片
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.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
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;

@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");
        // 配置不會被攔截的鏈接 順序判斷,在 ShiroConfiguration 中的 shiroFilter 處配置了 /ajaxLogin=anon,意味著可以不需要認證也可以訪問
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/*.html", "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(1024);//散列的次數,比如散列兩次,相當於 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
     *
     * 使用的是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實現
     * 
     * 使用的是shiro-redis開源插件
     *
     * @return
     */
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        return redisCacheManager;
    }

    /**
     * RedisSessionDAO shiro sessionDao層的實現 通過redis
     * 
     * 使用的是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();
    }

    //自動創建代理,沒有這個鑒權可能會出錯
    @Bean
    public DefaultAdvisorAutoProxyCreator getDefaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        autoProxyCreator.setProxyTargetClass(true);
        return autoProxyCreator;
    }
}
技術分享圖片

3.安全認證和權限驗證的核心,自定義Realm

技術分享圖片
import com.google.gson.JsonObject;
import com.test.cbd.service.UserService;
import com.test.cbd.vo.SysPermission;
import com.test.cbd.vo.SysRole;
import com.test.cbd.vo.UserInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
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.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;


public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private UserService userInfoService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
//        // 權限信息對象info,用來存放查出的用戶的所有的角色(role)及權限(permission)
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Session session = SecurityUtils.getSubject().getSession();
        UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
        // 用戶的角色集合
        Set<String> roles = new HashSet<>();
        roles.add(user.getRoleList().get(0).getRole());
        authorizationInfo.setRoles(roles);
        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);
        // Subject subject = SecurityUtils.getSubject();
        // Session session = subject.getSession();
        // session.setAttribute("role",userInfo.getRoleList());
        // System.out.println("----->>userInfo="+userInfo);
        if (userInfo == null) {
            return null;
        }
        if (userInfo.getState() == 1) { //賬戶凍結
            throw new LockedAccountException();
        }
        String credentials = userInfo.getPassword();
        System.out.println("credentials="+credentials);
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo.getUserName(), //用戶名
                credentials, //密碼
                credentialsSalt,
                getName()  //realm name
        );
        Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("USER_SESSION", userInfo);
        return authenticationInfo;
    }

}
技術分享圖片

4.全局異常處理器

技術分享圖片
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; } }
技術分享圖片

5.因為現在的項目大多都是前後端分離的,所以我們需要實現自己的session管理

技術分享圖片
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;


public class MySessionManager extends DefaultWebSessionManager {

    private static final String TOKEN = "token";

    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(TOKEN);
        //如果請求頭中有 token 則其值為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);
        }
    }
}
技術分享圖片

6.控制器

技術分享圖片
import com.alibaba.fastjson.JSONObject;
import com.test.cbd.vo.UserInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

@Slf4j
@Api(value="shiro測試",description="shiro測試")
@RestController
@RequestMapping("/")
public class ShiroLoginController {

    /**
     * 登錄測試
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/ajaxLogin", method = RequestMethod.POST)
    @ResponseBody
    public String ajaxLogin(UserInfo userInfo) {
        JSONObject jsonObject = new JSONObject();
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUserName(), userInfo.getPassword());
        Subject subject = SecurityUtils.getSubject();
        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();
    }

    /**
     * 鑒權測試
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ResponseBody
    @RequiresRoles("guest")
    public String check() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("msg", "鑒權測試");
        return jsonObject.toString();
    }
}
技術分享圖片

常用註解
@RequiresGuest 代表無需認證即可訪問,同理的就是 /path=anon

@RequiresAuthentication 需要認證,只要登錄成功後就允許你操作

@RequiresPermissions 需要特定的權限,沒有則拋出 AuthorizationException

@RequiresRoles 需要特定的橘色,沒有則拋出 AuthorizationException


7.以上就是shiro登陸和鑒權的主要配置和類,下面補充一下其他信息。

①application.properties中shiro-redis相關配置:

spring.redis.shiro.host=127.0.0.1
spring.redis.shiro.port=6379
spring.redis.shiro.timeout=5000
spring.redis.shiro.password=123456

②因為數據是模擬的,所以在登陸認證的時候,並沒有通過數據庫查用戶信息,可以通過以下方式模擬加密後的密碼:

技術分享圖片
    /**
     * 生成測試用的md5加密的密碼
     * @param args
     */
    public static void main(String[] args) {
        String hashAlgorithmName = "md5";
        String credentials = "123456";//密碼
        int hashIterations = 1024;
        ByteSource credentialsSalt = ByteSource.Util.bytes("root");//賬號
        String  obj = new SimpleHash(hashAlgorithmName, credentials, credentialsSalt, hashIterations).toHex();
        System.out.println(obj);
    }
技術分享圖片

上面obj的結果是b1ba853525d0f30afe59d2d005aad96c

③登陸認證的findByUsername方法,模擬到數據庫查詢用戶信息,實際是自己構造的數據,偷偷懶。

技術分享圖片
    public UserInfo findByUsername(String userName){
        SysRole admin = SysRole.builder().role("admin").build();
        List<SysPermission> list=new ArrayList<SysPermission>();
        SysPermission sysPermission=new SysPermission("read");
        SysPermission sysPermission1=new SysPermission("write");
        list.add(sysPermission);
        list.add(sysPermission1);
        admin.setPermissions(list);
        UserInfo root = UserInfo.builder().userName("root").password("b1ba853525d0f30afe59d2d005aad96c").credentialsSalt("123").state(0).build();
        List<SysRole> roleList=new ArrayList<SysRole>();
        roleList.add(admin);
        root.setRoleList(roleList);
        return root;
    }
技術分享圖片

8.結果演示

輸入正確的賬號密碼時,返回信息如下:

技術分享圖片

故意輸錯密碼時,返回信息如下:

技術分享圖片

鑒權時,如果該用戶沒有角色:

技術分享圖片

SpringBoot整合Shiro自定義Redis存儲