• 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
  • 相关阅读:
    Prometheus监控Kafka(三种方法JMX/Kafka_exporter/KMINION监控Kafka)
    信息系统项目管理师---第七章项目成本管理历年考题
    【ENVI精讲】遥感影像预处理-坐标系定义
    STM32MP157汇编流水灯
    腾讯云4核8G和2核4G服务器五年优惠价格表
    ASW3410数据手册|ASW3410设计参数|USB3.0高速数据开关切换IC说明书
    前端部署iis后axios跨域请求问题
    线性回归(Linear Regression)(机器学习)
    HTML5和CSS3的一些重要特性
    C语言——分支语句和循环语句
  • 原文地址:https://blog.csdn.net/u014042146/article/details/128155116