欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot配置shiro安全框架的实现

程序员文章站 2022-06-25 18:53:33
首先引入pom org.springframework.boot<...

首先引入pom

  <!--springboot 2.1.0-->
  <parent>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-parent</artifactid>
   <version>2.1.0.release</version>
  </parent>
  <!--shiro-->
  <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>
  <!-- shiro-redis -->
  <dependency>
   <groupid>org.crazycake</groupid>
   <artifactid>shiro-redis</artifactid>
   <version>3.1.0</version>
  </dependency>
  
  <!-- shiro-freemarker-tag -->
  <dependency>
   <groupid>net.mingsoft</groupid>
   <artifactid>shiro-freemarker-tags</artifactid>
   <version>1.0.0</version>
  </dependency>
  
  <!-- freemarker -->
  <dependency>
   <groupid>org.springframework.boot</groupid>
   <artifactid>spring-boot-starter-freemarker</artifactid>
  </dependency>

shiroconfig.java

package com.jx.cert.web.framework.config.shiro;

import java.util.linkedhashmap;
import java.util.map;

import javax.servlet.filter;

import org.apache.shiro.authc.credential.hashedcredentialsmatcher;
import org.apache.shiro.cache.memoryconstrainedcachemanager;
import org.apache.shiro.mgt.securitymanager;
import org.apache.shiro.session.mgt.sessionmanager;
import org.apache.shiro.spring.lifecyclebeanpostprocessor;
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.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.dependson;

import com.jx.cert.web.framework.config.shiro.filter.kickoutsessioncontrolfilter;
import com.jx.cert.web.framework.config.shiro.filter.shiropermissionsfilter;
import com.jx.cert.web.framework.config.shiro.filter.systemlogoutfilter;
import com.jx.common.utils.cacheconstants;


/**
* @classname: gyu  
* @description: todo(shrio配置)  
* @author gangyu
* @date 2018年12月4日 下午2:28:07  
 */
@configuration
public class shiroconfig {
 logger log=loggerfactory.getlogger(shiroconfig.class);
 @value("${spring.redis.host}")
    private string host;
    @value("${spring.redis.prot}")
    private int port;
    @value("${spring.redis.timeout}")
    private int timeout;
    @value("${spring.redis.password}")
    private string password;
    @value("${spring.redis.database}")
    private int database;

    //注意这里需要设置成 static 否则 @value 注入不了数据
    @bean(name = "lifecyclebeanpostprocessor")
    public static lifecyclebeanpostprocessor lifecyclebeanpostprocessor() {
        return new lifecyclebeanpostprocessor();
    }

    @bean(name = "shirofilter")
    public shirofilterfactorybean shirfilter(securitymanager securitymanager) {
  shirofilterfactorybean shirofilterfactorybean = new shirofilterfactorybean();
  log.debug("-----------------shiro拦截器工厂类注入开始");

  map<string,filter> filtermap=shirofilterfactorybean.getfilters();
  //权限过滤器
  filtermap.put("perms", new shiropermissionsfilter());
  
  shirofilterfactorybean.setfilters(filtermap);
  
  // 配置shiro安全管理器 securitymanager
  shirofilterfactorybean.setsecuritymanager(securitymanager);

  // 指定要求登录时的链接
  shirofilterfactorybean.setloginurl("/login");
  // 登录成功后要跳转的链接
  shirofilterfactorybean.setsuccessurl("/index");
  
  // filterchaindefinitions拦截器=map必须用:linkedhashmap,因为它必须保证有序
  map<string, string> filterchaindefinitionmap = new linkedhashmap<string, string>();
  
  //对外应用开发接口不验证
  filterchaindefinitionmap.put("/app/**", "anon");
        filterchaindefinitionmap.put("/ajaxlogin", "anon");
        // 放开验证码
  filterchaindefinitionmap.put("/public/getgifcode", "anon");
  // 退出
  filterchaindefinitionmap.put("/logout", "logout");
  
  //todo 全部放行
//  filterchaindefinitionmap.put("/manage/**", "anon[*]");

  //公共资源
        filterchaindefinitionmap.put("/static/**", "anon");
        filterchaindefinitionmap.put("/css/**", "anon");
        filterchaindefinitionmap.put("/img/**", "anon");
        filterchaindefinitionmap.put("/js/**", "anon");
        

  // authc:所有url都必须认证通过才可以访问;
  filterchaindefinitionmap.put("/**", "authc");
  shirofilterfactorybean.setfilterchaindefinitionmap(filterchaindefinitionmap);
  log.debug("-----------------shiro拦截器工厂类注入成功");
  return shirofilterfactorybean;
    }
    
    @bean
    public hashedcredentialsmatcher hashedcredentialsmatcher() {
        hashedcredentialsmatcher hashedcredentialsmatcher = new hashedcredentialsmatcher();
        hashedcredentialsmatcher.sethashalgorithmname("md5");//散列算法:这里使用md5算法;
        hashedcredentialsmatcher.sethashiterations(1);//散列的次数,比如散列两次,相当于 md5(md5(""));
        return hashedcredentialsmatcher;
    }

    //权限缓存到内存
    @bean(name = "shirorealm")
    @dependson("lifecyclebeanpostprocessor")
    public myshirorealm myshirorealm() {
        myshirorealm myshirorealm = new myshirorealm();
        myshirorealm.setcachemanager(new memoryconstrainedcachemanager());
        myshirorealm.setcredentialsmatcher(hashedcredentialsmatcher());
        return myshirorealm;
    }

    
    @bean(name = "securitymanager")
    public securitymanager securitymanager() {
        defaultwebsecuritymanager securitymanager = new defaultwebsecuritymanager();
        securitymanager.setrealm(myshirorealm());
        // 自定义session管理 使用redis
        securitymanager.setsessionmanager(sessionmanager());
        // 自定义缓存实现 使用redis
        securitymanager.setcachemanager(cachemanager());
        return securitymanager;
    }
    
    /**
     * 配置shiro redismanager
     * @return
     */
    public redismanager redismanager() {
        redismanager redismanager = new redismanager();
        redismanager.sethost(host);
        redismanager.setport(port);
        redismanager.settimeout(timeout);
//        redismanager.setpassword(password);
        redismanager.setdatabase(database);
        return redismanager;
    }
    
    //自定义sessionmanager
    @bean
    public sessionmanager sessionmanager() {
        mysessionmanager mysessionmanager = new mysessionmanager();
        mysessionmanager.setsessiondao(redissessiondao());
        //默认1个小时session过期
        mysessionmanager.setglobalsessiontimeout(cacheconstants.shiro_session_ms);
        return mysessionmanager;
    }

    /**
     * redissessiondao shiro sessiondao层的实现 通过redis
     */
    @bean
    public redissessiondao redissessiondao() {
        redissessiondao redissessiondao = new redissessiondao();
        redissessiondao.setredismanager(redismanager());
        return redissessiondao;
    }

    /**
     * cachemanager 缓存 redis实现
     * @return
     */
    @bean
    public rediscachemanager cachemanager() {
        rediscachemanager rediscachemanager = new rediscachemanager();
        rediscachemanager.setredismanager(redismanager());
        rediscachemanager.setexpire(cacheconstants.user_data_ttl);
        return rediscachemanager;
    }    
}

myshirorealm.java

package com.jx.cert.web.framework.config.shiro;

import java.util.arraylist;
import java.util.list;

import org.apache.commons.codec.digest.digestutils;
import org.apache.shiro.authc.authenticationexception;
import org.apache.shiro.authc.authenticationinfo;
import org.apache.shiro.authc.authenticationtoken;
import org.apache.shiro.authc.lockedaccountexception;
import org.apache.shiro.authc.simpleauthenticationinfo;
import org.apache.shiro.authc.unknownaccountexception;
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.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;

import com.jx.cert.web.framework.config.shiro.exception.sysusrenotloginappexception;
import com.jx.cert.web.framework.config.shiro.exception.systemnotexistexception;
import com.jx.common.utils.syscode;
import com.jx.core.api.model.vo.cert.syspermission;
import com.jx.core.api.model.vo.cert.sysrole;
import com.jx.core.api.model.vo.cert.syssystem;
import com.jx.core.api.model.vo.cert.sysuser;
import com.jx.core.api.service.business.cert.syspermissionservice;
import com.jx.core.api.service.business.cert.sysroleservice;
import com.jx.core.api.service.business.cert.syssystemservice;
import com.jx.core.api.service.business.cert.sysuserservice;

public class myshirorealm extends authorizingrealm {

    private logger logger = loggerfactory.getlogger(myshirorealm.class);

    @autowired
    private sysuserservice sysuserservice;
    @autowired
    private sysroleservice sysroleservice;
    @autowired
    private syspermissionservice syspermissionservice;
    @autowired
    private syssystemservice systemservice;
    
    

    @override
    protected authorizationinfo dogetauthorizationinfo(principalcollection principals) {
        logger.info("####################开始配置权限####################");
        sysuser user = (sysuser) principals.getprimaryprincipal();
        if (user != null) {
            //权限信息对象info,用来存放查出的用户的所有的角色(role)及权限(permission)
            simpleauthorizationinfo authorizationinfo = new simpleauthorizationinfo();
            list<string> rolestrlist = new arraylist<string>();//用户的角色集合
            list<string> perminsstrlist = new arraylist<string>();//用户的菜单权限集合
            for (sysrole role : user.getrolelist()) {
                rolestrlist.add(role.getrolename());
            }
            for (syspermission permission : user.getpermisslist()) {
                perminsstrlist.add(permission.geturl());
            }
            //用户的角色集合
            authorizationinfo.addroles(rolestrlist);
            //用户的菜单按钮权限集合
            authorizationinfo.addstringpermissions(perminsstrlist);
            return authorizationinfo;
        }
        return null;
    }

    /*主要是用来进行身份认证的,也就是说验证用户输入的账号和密码是否正确。*/
    @override
    protected authenticationinfo dogetauthenticationinfo(authenticationtoken token)
            throws authenticationexception {
        logger.info("####################身份认证####################");
        string userstr = (string) token.getprincipal();
       
     sysuser user = sysuserservice.getuserbyusername(username);
     
        //认证系统用户
        list<sysrole> rolelist = sysroleservice.findrolebyuserid(user.getuserid(),systemid);
        user.setrolelist(rolelist);//获取用户角色
        list<syspermission> list=syspermissionservice.getuserpermission(user.getuserid(),systemid);
        syspermission permis=new syspermission();
        list.add(permis);
        user.setpermisslist(list);//获取用户权限
     
  return new simpleauthenticationinfo(user, digestutils.md5hex(user.getpassword()),getname());
    }
}

shirotagsfreemarkercfg.java

package com.jx.cert.web.framework.config.shiro;

import javax.annotation.postconstruct;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.component;
import org.springframework.web.servlet.view.freemarker.freemarkerconfigurer;

import com.jagregory.shiro.freemarker.shirotags;

import freemarker.template.templatemodelexception;

/**  
* @classname: shirotagsfreemarkercfg  
* @description: todo(ftl shiro 标签)  
* @author gangyu
* @date 2018年12月5日 下午5:16:27  
*    
*/
@component
public class shirotagsfreemarkercfg {

    @autowired
    private freemarkerconfigurer freemarkerconfigurer;

    @postconstruct
    public void setsharedvariable() throws templatemodelexception {
        freemarkerconfigurer.getconfiguration().setsharedvariable("shiro", new shirotags());
    }
}

shiropermissionsfilter.java

/**    
* @title: shiropermissionsfilter.java  
* @package com.jx.cert.web.config.shiro  
* @description: todo(用一句话描述该文件做什么)  
* @author gangyu
* @date 2018年12月5日 上午11:47:00  
* @version v1.0    
*/
package com.jx.cert.web.framework.config.shiro.filter;

import java.io.ioexception;
import java.io.printwriter;
import java.util.list;

import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;

import org.apache.shiro.web.filter.authz.permissionsauthorizationfilter;
import org.slf4j.logger;
import org.slf4j.loggerfactory;

import com.google.gson.gson;
import com.jx.cert.web.framework.config.shiro.shiroutil;
import com.jx.common.utils.result;
import com.jx.common.utils.enums.codeenum;
import com.jx.core.api.model.vo.cert.syspermission;
import com.jx.core.api.model.vo.cert.sysuser;

/**  
* @classname: shiropermissionsfilter  
* @description: todo(权限验证)  
* @author gangyu
* @date 2018年12月5日 上午11:47:00  
*/
public class shiropermissionsfilter extends permissionsauthorizationfilter {

    private static final logger logger = loggerfactory.getlogger(shiropermissionsfilter.class);
    
    /**
     * 权限检测验证
     */
    @override
    protected boolean onaccessdenied(servletrequest servletrequest, servletresponse servletresponse) throws ioexception {
        logger.info("----------权限校验-------------");
        httpservletrequest request = (httpservletrequest) servletrequest;
        httpservletresponse response = (httpservletresponse) servletresponse;
        string requrl=request.getrequesturi();
        list<syspermission> permslist=shiroutil.getuser().getpermisslist();
        string contextpath=request.getcontextpath();
        requrl=requrl.substring(contextpath.length()+1, requrl.length());
        string header = request.getheader("x-requested-with");
        boolean isajax = "xmlhttprequest".equals(header);
        sysuser user=shiroutil.getuser();
    if(!new gson().tojson(permslist).contains(requrl)){
            if (isajax) {
                logger.info("----------ajax请求拒绝-------------");
                response.setcharacterencoding("utf-8");
                response.setcontenttype("application/json");
                response.getwriter().write(new gson().tojson(new result(codeenum.not_permission)));
            } else {
                logger.info("----------普通请求拒绝-------------");
                response.sendredirect(request.getcontextpath()+"/403");
            }
            return false;
        }else {
         return true;
        }
    }
}

shiroutil.java

package com.jx.cert.web.framework.config.shiro;

import org.apache.shiro.securityutils;
import org.apache.shiro.session.session;
import org.apache.shiro.subject.subject;

import com.jx.core.api.model.vo.cert.sysuser;


public class shiroutil {
    /**
     * 获取当前 subject
     *
     * @return
     */
    public static subject getsubject() {
        return securityutils.getsubject();
    }

    /**
     * 获取shiro指定的sessionkey
     *
     * @param key
     * @param <t>
     * @return
     */
    public static <t> t getsessionattr(string key) {
        session session = getsession();
        return session != null ? (t) session.getattribute(key) : null;
    }

    /**
     * 设置shiro指定的sessionkey
     *
     * @param key
     * @param value
     */
    public static void setsessionattr(string key, object value) {
        session session = getsession();
        session.setattribute(key, value);
    }

    /**
     * 获取当前用户对象
     *
     * @return
     */
    public static sysuser getuser() {
     if(getsubject().isauthenticated()){
            return (sysuser) getsubject().getprincipals().getprimaryprincipal();
     }
     return null;
    }
    /**
     * 获取当前用户对象userid
     *
     * @return
     */
    public static string getuserid() {
        return getuser().getuserid();
    }

    /**
     * 移除shiro指定的sessionkey
     *
     * @param key
     */
    public static void removesessionattr(string key) {
        session session = getsession();
        if (session != null)
            session.removeattribute(key);
    }

    /**
     * 验证当前用户是否属于该角色
     *
     * @param rolename 角色名称
     * @return 属于该角色:true,否则false
     */
    public static boolean hasrole(string rolename) {
        return getsubject() != null && rolename != null
                && rolename.length() > 0 && getsubject().hasrole(rolename);
    }

    /**
     * shiro 中获取session
     *
     * @return session
     */
    public static session getsession() {
        return getsubject().getsession();
    }

    /**
     * 验证当前用户是否属于以下所有角色
     * 多权限“,”分割
     *
     * @param rolenames 权限名称
     * @return 属于:true,否则false
     */
    public static boolean hasallroles(string rolenames) {
        boolean hasallrole = true;
        subject subject = getsubject();
        if (subject != null && rolenames != null && rolenames.length() > 0) {
            for (string role : rolenames.split(",")) {
                if (!subject.hasrole(role.trim())) {
                    hasallrole = false;
                    break;
                }
            }
        }
        return hasallrole;
    }

    /**
     * 验证当前用户是否属于以下任意一个角色
     * 多权限“,”分割
     * @param rolenames
     * @return
     */
    public static boolean hasanyroles(string rolenames) {
        boolean hasanyrole = false;
        subject subject = getsubject();
        if (subject != null && rolenames != null && rolenames.length() > 0) {
            for (string role : rolenames.split(",")) {
                if (subject.hasrole(role.trim())) {
                    hasanyrole = true;
                    break;
                }
            }
        }
        return hasanyrole;
    }
}

到此这篇关于springboot配置shiro安全框架的实现的文章就介绍到这了,更多相关springboot配置shiro内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!