文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

SpringBoot如何配置shiro安全框架

2023-06-14 20:55

关注

这篇文章主要介绍了SpringBoot如何配置shiro安全框架,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

springboot是什么

springboot一种全新的编程规范,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,SpringBoot也是一个服务于框架的框架,服务范围是简化配置文件。

首先引入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;@Configurationpublic 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    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;    }        @Bean    public RedisSessionDAO redisSessionDAO() {        RedisSessionDAO redisSessionDAO = new RedisSessionDAO();        redisSessionDAO.setRedisManager(redisManager());        return redisSessionDAO;    }        @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;@Componentpublic class ShiroTagsFreeMarkerCfg {    @Autowired    private FreeMarkerConfigurer freeMarkerConfigurer;    @PostConstruct    public void setSharedVariable() throws TemplateModelException {        freeMarkerConfigurer.getConfiguration().setSharedVariable("shiro", new ShiroTags());    }}

ShiroPermissionsFilter.java

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;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 {        public static Subject getSubject() {        return SecurityUtils.getSubject();    }        public static <T> T getSessionAttr(String key) {        Session session = getSession();        return session != null ? (T) session.getAttribute(key) : null;    }        public static void setSessionAttr(String key, Object value) {        Session session = getSession();        session.setAttribute(key, value);    }        public static SysUser getUser() {     if(getSubject().isAuthenticated()){            return (SysUser) getSubject().getPrincipals().getPrimaryPrincipal();     }     return null;    }        public static String getUserId() {        return getUser().getUserId();    }        public static void removeSessionAttr(String key) {        Session session = getSession();        if (session != null)            session.removeAttribute(key);    }        public static boolean hasRole(String roleName) {        return getSubject() != null && roleName != null                && roleName.length() > 0 && getSubject().hasRole(roleName);    }        public static Session getSession() {        return getSubject().getSession();    }        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;    }        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安全框架”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯