• Shiro-SpringBoot (一)


    前不久负责项目中刚好也使用了Shiro做权限控制,趁着空闲期想把之前做的整理一下。在日常项目开发中,权限认证是不可少的模块。比较常用的有Spring Security,或是轻量级的Apache Shiro。相对来说Shiro提供了认证、授权、加密、会话管理、与Web集成、缓存等。这些都是日常会用到的,而且Shiro的API比较简洁,学习成本相对低。接下来将整理一下在SpringBoot中如何集成Shiro:

    • RBAC介绍
    • SpringBoot集成Shiro和配置
    • Shiro的登录和认证
    • 当前不足点

    (一) RBAC介绍

    **RBAC(Role-Based Access Control )**基于角色访问控制,在权限设计上用户是基于角色进行权限认证,而角色又是和资源相关联的。这样在设计和管理上简化了权限的操作,它们都是层级依赖,更方便我们的管理。如此一来,数据库表设计可以如下图:
    cmd-markdown-logo

    (二) SpringBoot集成Shiro和配置

    1、导入Shiro依赖

    pom.xml中加入以下依赖

    <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>1.2.5</version>
    </dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2、配置Shiro

    在配置之前,首先了解一下Shiro中主要功能,并看看它们主要是做什么的。

    • Subject 安全视角下与软件交互的实体(用户,第三方服务等等)
    • Authenticator 用户登录时进行账户的认证
    • Authorizer 用户登录时进行账户的权限资源认证
    • Realms每当执行认证或授权时,shiro会从程序配置的一个或多个Realm中查询

    新建JAVAShiroRealm用于继承ShiroAuthorizingRealm抽象类,并复写doGetAuthenticationInfodoGetAuthorizationInfo用于账户和权限的认证。

    public class ShiroRealm extends AuthorizingRealm {
       
    
        @Autowired
        private UserService userService;
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
       
            UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
            String userName = token.getUsername();
            String password = new String((char[])token.getCredentials());
            //这里可以自行查询数据库进行验证
            if(userName != "zhangshan" && password != DigestUtils.md5Hex("123456")) {
       
                throw new UnknownAccountException ("未知的账户认证失败");
            }
            SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                    userName, //用户名
                    DigestUtils.md5Hex("123456"), 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
  • 相关阅读:
    王者荣耀太空人名字怎么弄 王者荣耀太空人名字设置方法
    WinScope跟踪window/layer pb文件
    数据结构——计数与归并非递归
    【原创佳作】介绍Pandas实战中一些高端玩法
    数据结构-Prim算法构造无向图的最小生成树
    【面向对象程序设计】Java大作业 汽车租赁管理系统V4.0
    LC844. 比较含退格的字符串
    【ElasticSearch】学习笔记
    04A中断的配置
    go-micro教程 — 第一章 快速入门
  • 原文地址:https://blog.csdn.net/u014042146/article/details/128155116