当前位置:

首页 > 软件教程 > SpringBoot整合Shiro权限管理教程

SpringBoot整合Shiro权限管理教程

让我们开始SpringBoot-09Shiro的HelloShiro教程。我们将从创建一个简单的Maven项目开始,然后逐步搭建Shiro环境。创建一个简单的Maven项目首先,我们需要创建一个最基本的Maven项目。导入依赖接下来,我们需要在pom.xml中添加以下依赖:<dependencies><dependency><groupId>org.apache.shiro</groupId><arti

本文目录

    让我们开始SpringBoot-09 Shiro的Hello Shiro教程。我们将从创建一个简单的Maven项目开始,然后逐步搭建Shiro环境。

    1. 创建一个简单的Maven项目

    首先,我们需要创建一个最基本的Maven项目。

    1. 导入依赖

    接下来,我们需要在pom.xml中添加以下依赖:

    
        
            org.apache.shiro
            shiro-core
            1.7.0
        
        
            org.slf4j
            jcl-over-slf4j
            2.0.0-alpha1
        
        
            org.slf4j
            slf4j-log4j12
            2.0.0-alpha1
        
        
            log4j
            log4j
            1.2.17
        
    
    1. 创建log4j.properties

    为了配置日志,我们需要创建log4j.properties文件:

    log4j.rootLogger=INFO, stdout
    log4j.appender.stdout=org.apache.log4j.ConsoleAppender
    log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
    log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n
    # General Apache libraries
    log4j.logger.org.apache=WARN
    # Spring
    log4j.logger.org.springframework=WARN
    # Default Shiro logging
    log4j.logger.org.apache.shiro=INFO
    # Disable verbose logging
    log4j.logger.org.apache.shiro.util.ThreadContext=WARN
    log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
    1. 创建shiro.ini

    创建shiro.ini文件来配置Shiro的用户和角色:

    [users]
    root = secret, admin
    guest = guest, guest
    presidentskroob = 12345, president
    darkhelmet = ludicrousspeed, darklord, schwartz
    lonestarr = vespa, goodguy, schwartz
    

    [roles] admin = schwartz = lightsaber: goodguy = winnebago:drive:eagle5

    1. 创建Quickstart类

    最后,我们创建一个Quickstart类来测试Shiro的功能:

    import org.apache.shiro.SecurityUtils;
    import org.apache.shiro.authc.*;
    import org.apache.shiro.config.IniSecurityManagerFactory;
    import org.apache.shiro.mgt.SecurityManager;
    import org.apache.shiro.session.Session;
    import org.apache.shiro.subject.Subject;
    import org.apache.shiro.util.Factory;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;

    public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class);

    public static void main(String[] args) {
        // The easiest way to create a Shiro SecurityManager with configured
        // realms, users, roles and permissions is to use the simple INI config.
        // We'll do that by using a factory that can ingest a .ini file and
        // return a SecurityManager instance:
        // Use the shiro.ini file at the root of the classpath
        // (file: and url: prefixes load from files and urls respectively):
        Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        SecurityManager securityManager = factory.getInstance();
    
        // for this simple example quickstart, make the SecurityManager
        // accessible as a JVM singleton.  Most applications wouldn't do this
        // and instead rely on their container configuration or web.xml for
        // webapps.  That is outside the scope of this simple quickstart, so
        // we'll just do the bare minimum so you can continue to get a feel
        // for things.
        SecurityUtils.setSecurityManager(securityManager);
    
        // Now that a simple Shiro environment is set up, let's see what you can do:
        // get the currently executing user:
        Subject currentUser = SecurityUtils.getSubject();
    
        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            log.info("Retrieved the correct value! [" + value + "]");
        }
    
        // let's login the current user so we can check against roles and permissions:
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
            token.setRememberMe(true);
            try {
                currentUser.login(token);
            } catch (UnknownAccountException uae) {
                log.info("There is no user with username of " + token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
                log.info("Password for account " + token.getPrincipal() + " was incorrect!");
            } catch (LockedAccountException lae) {
                log.info("The account for username " + token.getPrincipal() + " is locked.  " +
                        "Please contact your administrator to unlock it.");
            }
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            }
        }
    
        //say who they are:
        //print their identifying principal (in this case, a username):
        log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
    
        //test a role:
        if (currentUser.hasRole("schwartz")) {
            log.info("May the Schwartz be with you!");
        } else {
            log.info("Hello, mere mortal.");
        }
    
        //test a typed permission (not instance-level)
        if (currentUser.isPermitted("lightsaber:wield")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }
    
        //a (very powerful) Instance Level permission:
        if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }
    
        //all done - log out!
        currentUser.logout();
    
        System.exit(0);
    }

    }

    1. 启动测试

    SpringBoot-09  Shiro

    1. 可能遇到错误

    SpringBoot-09  Shiro

    解决办法:

    这是因为依赖中的问题。将以下依赖的scope标签删除:

    
    org.slf4j
    jcl-over-slf4j
    2.0.0-alpha1
    
    
    
    org.slf4j
    slf4j-log4j12
    2.0.0-alpha1
    
    

    Shiro环境搭建

    Shiro环境搭建需要三个要素:

    1. ShiroFilterFactoryBean
    2. DefaultWebSecurityManager
    3. Realm

    我们需要倒着来创建。

    创建config文件夹和ShiroConfig、UserRealm类

    首先,创建UserRealm类:

    public class UserRealm extends AuthorizingRealm {
    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        return null;
    }

    }

    然后,创建ShiroConfig类:

    @Configuration
    public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
    ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
    //设置安全管理器
    bean.setSecurityManager(defaultWebSecurityManager);
    return bean;
    }

    //DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }
    
    //创建 realm 对象
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    }

    这样,我们就完成了SpringBoot-09 Shiro的Hello Shiro教程的基本步骤。接下来,您可以根据需要进一步扩展和配置Shiro的功能。

    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    软件教程 html
    相关文章 更多
    html写提交成功页面代码及完整实现方法
    html写提交成功页面代码及完整实现方法

    详解HTML提交成功页面的标准代码结构与实现逻辑,涵盖静态提示、自动跳转脚本及防止重复提交的策略,帮助开发者构建友好的表单交互终点。

    PS网页版直接使用
    PS网页版直接使用

    PS网页版免费官方入口为https://www.adobe.com/products/photoshop/web.html,支持PSD编辑、实时协作、多色彩空间、智能抠图、AI修复、跨端同步、中文引导及SVG/PSD兼容等核心功能。 对于很多设计新手,或者只是偶尔需要处理图片的朋友来说,直接在线、免

    淘宝网页版入口查找教程
    淘宝网页版入口查找教程

    淘宝官方网页登录入口 对于如何找到淘宝网页版的入口,很多朋友都感到有点摸不着头脑。别急,这篇文章就来为你拆解清楚整个登录流程。官方的登录入口很明确,就在官网首页的左上角。 淘宝网页版入口位于官网首页左上角,点击“亲,请登录”即可跳转至统一的验证页面。登录支持密码、短信验证码和手机APP扫码三种方式,

    怎样在无忧小说网中查看阅读进度
    怎样在无忧小说网中查看阅读进度

    在无忧小说网,如何精准掌握你的阅读进度? 在无忧小说网追更小说,最怕的就是忘了上次读到哪儿。如果感觉界面没有清晰显示阅读进度,别急,这通常不是数据丢失,而是相关视图功能没有开启或找到。掌握下面这四条路径,你就能对阅读进度了如指掌。 一、通过阅读页面顶部状态栏查看 最简单直接的方法,其实就藏在眼皮底下

    AO3长期有效镜像地址
    AO3长期有效镜像地址

    AO3长期有效镜像地址是https://www.ao3cn.cc/,该地址支持多端适配、智能检索与创作者友好发布机制。 不少朋友都在四处打听,那个稳定的AO3入口到底在哪?别急,接下来要分享的,正是2026年依然能顺畅访问的最新地址,干货就在下面,一起来看看。 请认准这个链接:https

    Microsoft
    Microsoft

    Edge收藏夹不同步?五步排查法,让书签乖乖“串门” 跨设备工作,收藏夹却“各管各的”?这确实是件烦心事。你的Edge浏览器收藏夹没能同步到其他电脑或手机上,背后通常藏着几个常见的原因:账户登录状态、网络配置冲突,或者浏览器设置本身的小脾气。别担心,跟着下面的步骤走一遍,基本都能让书签重新“归队”,

    米侠浏览器打不开网页
    米侠浏览器打不开网页

    米侠浏览器页面打不开,或者干脆显示一片空白?问题根源大概率出在内核上。比如内核和当前网页的兼容性出了岔子、页面渲染模块意外损坏,再或者,内核版本实在太旧了。别急,沿着切换内核、清理缓存、关闭硬件加速、替换核心文件这四步走,通常都能解决。 用米侠浏览器上网,碰到页面死活刷不出来,或者只显示一个空白屏幕

    IE浏览器怀旧版在线网址
    IE浏览器怀旧版在线网址

    IE浏览器怀旧版在线网址:一次精准的技术时光回溯 最近,不少老用户和怀旧爱好者在反复搜索一个问题:那个经典的Internet Explorer,如今还能在哪里原汁原味地体验到?答案指向一个特定的地址:https://ie.microsoft.com/legacy/。 这个网站远不止是一个简单的“皮肤

    HTML转PDF在线官网
    HTML转PDF在线官网

    HTML转PDF在线官网入口:网页内容一键生成PDF指南 HTML转PDF在线官网入口是https://htmltopdf.com,支持HTML5标签、CSS渲染、多语言字符、Web字体;操作免注册,可预览、自定义参数、批量导出;输出300DPI、保留超链接与矢量图;本地处理保障隐私;兼容主流浏览器

    中国移动官网在线登录入口
    中国移动官网在线登录入口

    中国移动官网在线登录入口指引:功能、安全与体验全解析 说到在网上办理业务,第一步往往就是登录。对中国移动的用户而言,那个关键的入口在哪里呢?其实,答案很明确:http://login.10086.cn/html/login/login.html,这个直达地址就是您进入中国移动数字服务世界的官方大门。

    查看更多
    精品专题 更多
    装机必备
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows
    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程
    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版
    macOS

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版
    Windows/ macOS/ Linux

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版
    Windows/ macOS/ Linux

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版
    Windows

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。