springboot 整合 shiro 框架自定义登录验证和权限管理

本文介绍 springboot 项目整合 shiro 框架过程。

复制代码
项目版本信息:
jdk 1.8
springboot 2.7.18 
mysql 5.7

一、添加依赖

xml 复制代码
<!-- 添加依赖-->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring-boot-starter</artifactId>
    <version>1.9.0</version>
</dependency>
<!-- 添加mybatisplus依赖-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.0.5</version>
</dependency>
<!-- 添加mysql依赖-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>
<!-- 添加lombok依赖-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
<!-- 添加thymeleaf依赖-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

二、添加配置

yaml 复制代码
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:mapper/*.xml
spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/shirodemo?characterEncoding=utf-8&useSSL=false
    username: your_username
    password: your_password
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
shiro:
  loginUrl: /myController/login

三、创建数据库

sql 复制代码
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) DEFAULT NULL,
  `pwd` varchar(50) DEFAULT NULL,
  `rid` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

根据需求插入数据:

四、创建实体类

五、创建 mapper 接口

复制代码
使用了 mybatisplus ,只需要继承 BaseMapper 接口就能自动生成简单的 crud 操作。

六、创建业务层接口,并写出接口实现类

css 复制代码
注意加上 @service 注解

七、启动类添加 @MapperScan("com.yuqn.shiro_springboot.mapper") 注解,扫描 mapper 包下的接口。

复制代码
上述一至七,都是shiro进行登录认证和权限管理必备的前提。

八、自定义登录认证

8.1、创建自定义realm

需要继承 AuthorizingRealm 类,并且重写 doGetAuthenticationInfo 和 doGetAuthorizationInfo,其中 doGetAuthenticationInfo() 就是写自定义登录验证的方法, doGetAuthorizationInfo() 则是自定义授权方法,代码如下:

java 复制代码
/**
 * @author: yuqn
 * @Date: 2024/4/10 14:49
 * @description:
 * 自定义登录认证方法
 * @param: null
 * @return: null
 */
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    // 1、获取用户信息
    String name = authenticationToken.getPrincipal().toString();
    // 2、获取数据库用户信息
    User user = userService.getUserInfoByName(name);
    // 3、判断,将数据封装返回
    if (user != null){
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                authenticationToken.getPrincipal(),
                user.getPwd(),
                ByteSource.Util.bytes("yuqn"),
                authenticationToken.getPrincipal().toString()
        );
        System.out.println(info);
        return info;
    }
    return null;
}

8.2、创建配置类

通过配置类,创建一系列需要的对象(如加密器等)存储到realm中,并且配置 shiro 内置过滤器。

java 复制代码
@Configuration
public class ShiroConfig {

    @Resource
    private MyRealm myRealm;

    // 配置securitymanager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(){
        // 1、创建defaultWebSecurityManager对象
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 2、创建加密对象,设置相关属性
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        hashedCredentialsMatcher.setHashIterations(1);
        // 3、将加密对象存储到myRealm中
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        // 4、将myRealm存入到defaultWebSecurityManager对象
        defaultWebSecurityManager.setRealm(myRealm);
        // 5、返回
        return defaultWebSecurityManager;
    }

    // 配置shiro内置过滤器拦截范围
    @Bean
    public DefaultShiroFilterChainDefinition shiroFilterChainDefinition(){
        DefaultShiroFilterChainDefinition defaultShiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
        // 设置不认证可以访问的资源
        defaultShiroFilterChainDefinition.addPathDefinition("/myController/userLogin","anon");
        defaultShiroFilterChainDefinition.addPathDefinition("/login","anon");
        // 设置需要进行登录认证的拦截范围
        defaultShiroFilterChainDefinition.addPathDefinition("/**","authc");
        return defaultShiroFilterChainDefinition;
    }

}

8.3、添加控制器

创建控制器,用于接收前端请求并且做出处理。

less 复制代码
@Controller
@RequestMapping("myController")
public class MyController {
    @GetMapping("userLogin")
    @ResponseBody
    public String userLogin(String name,String pwd){
        // 1获取subject对象
        Subject subject = SecurityUtils.getSubject();
        // 2封装请求数据到token
        AuthenticationToken token = new UsernamePasswordToken(name,pwd);
        // 3调用login方法进行登录认证
        try{
            subject.login(token);
            return "登录成功";
        }catch(AuthenticationException e){
            e.printStackTrace();
            System.out.println("登录失败");
            return "登录失败";
        }

    }
}

这里使用 get 请求更方便,实际开发中不建议使用 get 请求进行登录,安全性较低。

8.4、浏览器测试

启动项目,通过浏览器访问地址 http://localhost:8080/myController/userLogin?name=admin&pwd=123456

通过浏览器访问地址 http://localhost:8080/myController/userLogin?name=admin&pwd=123123

复制代码
数据库里面的 admin 密码是使用 md5 进行一次加盐加密的,原数据为 123456,加盐为 yuqn。

8.4、不足之处

实际开发中,密码一般是从前端用户传递而来,为了安全,一般是前端进行处理后后传到后端,那么后端得到的基本就是加密后的密码了,只需要通过 shiro 进行验证即可。

九、权限管理

十、拓展

shiro 是一个安全的框架,主要用来进行登录验证、权限管理。

10.1、shiro有三大核心,分别是:

1、Subject: 代表了当前用户的操作,包含了用户的身份(Principals)和凭据(Credentials)。

2、SecurityManager: 是Shiro框架的核心,负责对所有的Subject进行管理,它是Shiro的守门神,管理着所有的安全操作。

3、Realm: 是Shiro与应用安全数据之间的桥梁,它负责获取安全数据(如用户、角色、权限)。

10.2、shiro 框架和 spring security 框架的区别:

1、shiro 是在 apache 下的工具, spring security 是在 spring 下的工具

2、shiro 不依赖任何框架, spring security 依赖 spring 框架

3、spring security 相比 shiro 更加复杂

4、因为 spring security 是在 spring 下,所以 spring security 能够更好地与spring mvc框架整合

相关推荐
北城笑笑3 分钟前
Server 18 ,Nginx 双服务器 HTTP转HTTPS 代理实战( HTTP 地址换 HTTPS 域名 )
运维·服务器·前端·后端·nginx·http·https
紫洋葱hh3 分钟前
Go 入门基础:类型、变量与运算符
开发语言·后端·ai·golang
IT研究室11 分钟前
最新计算机毕业设计选题推荐-基于spring boot的美食配送平台-网站-文档指导-Java-springboot
java·spring boot·课程设计
打工仔折腾 AI12 分钟前
Qt网络编程实战:UDP、TCP到HTTP的落地经验与选型
网络·人工智能·后端·python·qt·udp·ai agent 实战
打工仔折腾 AI13 分钟前
SQL 编辑器不是高级记事本:KStudio 与 KSQL Developer 的建表与增删改查手法
数据库·人工智能·后端·python·sql·编辑器·ai agent 实战
拖孩1 小时前
# AI 帮我写的小程序,上线不到一个月流量主突然爆了
前端·后端·微信小程序
考虑考虑1 小时前
JFROG手动上传包
运维·后端·自动化运维
省钱兄--zs2 小时前
无人自助拼豆系统架构设计与功能实现落地部署全流程实战指南
java·数据仓库·spring boot·系统架构·需求分析
Java爱好狂.2 小时前
挑战一周速通Spring+SpringBoot+SpringCloud!
java·后端·spring·springboot·架构师·java面试·java程序员
柠檬味拥抱2 小时前
基于 YOLO11 的 18 类户外生活垃圾智能检测系统:从模型到 Streamlit 全流程实战
后端