• SpringBoot 整合【MybatisPlus、Shiro】实现权限认证信息


    目录

    1. 添加依赖

    2. 建库建表

    3. 手动增加数据测试需要

    4. 生产代码 

    5. service模块

    5.1 IUserService

    5.2 UserServiceImpl

    6. MyRealm

    7. ShiroConfig

    8. controller

    9. 配置application.yml文件

    10. 配置启动类

    11. 启动项目开始测试


     1. 添加依赖

    1. <dependency>
    2. <groupId>com.baomidougroupId>
    3. <artifactId>mybatis-plus-boot-starterartifactId>
    4. <version>3.5.2version>
    5. dependency>
    6. <dependency>
    7. <groupId>com.baomidougroupId>
    8. <artifactId>mybatis-plus-generatorartifactId>
    9. <version>3.5.2version>
    10. dependency>
    11. <dependency>
    12. <groupId>org.springframework.bootgroupId>
    13. <artifactId>spring-boot-starter-freemarkerartifactId>
    14. <version>2.7.4version>
    15. dependency>
    16. <dependency>
    17. <groupId>org.springframework.bootgroupId>
    18. <artifactId>spring-boot-starter-jdbcartifactId>
    19. dependency>
    20. <dependency>
    21. <groupId>org.springframework.bootgroupId>
    22. <artifactId>spring-boot-starter-webartifactId>
    23. dependency>
    24. <dependency>
    25. <groupId>mysqlgroupId>
    26. <artifactId>mysql-connector-javaartifactId>
    27. <scope>runtimescope>
    28. dependency>
    29. <dependency>
    30. <groupId>org.projectlombokgroupId>
    31. <artifactId>lombokartifactId>
    32. <optional>trueoptional>
    33. dependency>
    34. <dependency>
    35. <groupId>org.springframework.bootgroupId>
    36. <artifactId>spring-boot-starter-thymeleafartifactId>
    37. dependency>
    38. <dependency>
    39. <groupId>org.apache.shirogroupId>
    40. <artifactId>shiro-spring-boot-web-starterartifactId>
    41. <version>1.9.0version>
    42. dependency>

    2. 建库建表

    1. CREATE DATABASE IF NOT EXISTS `shirodb` CHARACTER SET utf8mb4;
    2. USE `shirodb`;
    3. CREATE TABLE `user` (
    4. `id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
    5. `name` VARCHAR(30) DEFAULT NULL COMMENT '用户名',
    6. `pwd` VARCHAR(50) DEFAULT NULL COMMENT '密码',
    7. `rid` BIGINT(20) DEFAULT NULL COMMENT '角色编号',
    8. PRIMARY KEY (`id`)
    9. ) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='用户表';

    3. 手动增加数据测试需要

    •  先生成加密后的密码添加到数据库里 方便测试使用
    1. package com.jmh.springbootshiro.utls;
    2. import org.apache.shiro.crypto.hash.Md5Hash;
    3. public class ShiroMD5 {
    4. public static void main(String[] args) {
    5. String password = "1234";
    6. //为了保证安全,避免被破解还可以多次迭代加密,保证数据安全
    7. Md5Hash md53 = new Md5Hash(password,"salt",3);
    8. System.out.println("md5带盐的3次加密:"+md53.toHex());
    9. }
    10. }
    • 演示

     

    4. 生产代码 

    • 生成输出目录注意查看、修改 
    1. package com.jmh.springbootshiro.generator;
    2. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
    3. import com.baomidou.mybatisplus.generator.config.OutputFile;
    4. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
    5. import java.util.Collections;
    6. /**
    7. * @author 蒋明辉
    8. * @data 2022/9/28 19:48
    9. */
    10. public class MybatisPlusGenerator {
    11. public static void main(String[] args) {
    12. FastAutoGenerator.create(
    13. "jdbc:mysql://localhost:3306/shirodb?useUnicode=true&characterEncoding=UTF-8&useSSL=false",
    14. "root",
    15. "1234")
    16. .globalConfig(builder -> {
    17. builder.author("jmh") // 设置作者
    18. //.enableSwagger() // 开启 swagger 模式
    19. .fileOverride() // 覆盖已生成文件
    20. .outputDir("E:\\shiroProject\\springboot-shiro\\src\\main\\java"); // 指定输出目录
    21. })
    22. .packageConfig(builder -> {
    23. builder.parent("com.jmh.springbootshiro") // 设置父包名
    24. //.moduleName("system") // 设置父包模块名
    25. .pathInfo(Collections.singletonMap(OutputFile.xml, "E:\\shiroProject\\springboot-shiro\\src\\main\\resources\\mapper")); // 设置mapperXml生成路径
    26. })
    27. .strategyConfig(builder -> {
    28. builder.addInclude("user") // 设置需要生成的表名
    29. .addTablePrefix("t_", "c_"); // 设置过滤表前缀
    30. })
    31. .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
    32. .execute();
    33. }
    34. }
    • 自动生成目录结构 

     

     

    5. service模块

      5.1 IUserService

    1. package com.jmh.springbootshiro.service;
    2. import com.jmh.springbootshiro.entity.User;
    3. import com.baomidou.mybatisplus.extension.service.IService;
    4. /**
    5. *

    6. * 用户表 服务类
    7. *

    8. *
    9. * @author jmh
    10. * @since 2022-11-13
    11. */
    12. public interface IUserService extends IService {
    13. /**
    14. * 根据用户名查询信息
    15. */
    16. User queryUserInfoByName(String name);
    17. }

      5.2 UserServiceImpl

    1. package com.jmh.springbootshiro.service.impl;
    2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    3. import com.jmh.springbootshiro.entity.User;
    4. import com.jmh.springbootshiro.mapper.UserMapper;
    5. import com.jmh.springbootshiro.service.IUserService;
    6. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.stereotype.Service;
    9. /**
    10. *

    11. * 用户表 服务实现类
    12. *

    13. *
    14. * @author jmh
    15. * @since 2022-11-13
    16. */
    17. @Service
    18. public class UserServiceImpl extends ServiceImpl implements IUserService {
    19. @Autowired
    20. private UserMapper userMapper;
    21. @Override
    22. public User queryUserInfoByName(String name) {
    23. QueryWrapper queryWrapper=new QueryWrapper<>();
    24. queryWrapper.eq("name",name);
    25. return userMapper.selectOne(queryWrapper);
    26. }
    27. }

    6. MyRealm

    1. package com.jmh.springbootshiro.utls;
    2. import com.jmh.springbootshiro.entity.User;
    3. import com.jmh.springbootshiro.service.IUserService;
    4. import org.apache.shiro.authc.AuthenticationException;
    5. import org.apache.shiro.authc.AuthenticationInfo;
    6. import org.apache.shiro.authc.AuthenticationToken;
    7. import org.apache.shiro.authc.SimpleAuthenticationInfo;
    8. import org.apache.shiro.authz.AuthorizationInfo;
    9. import org.apache.shiro.realm.AuthorizingRealm;
    10. import org.apache.shiro.subject.PrincipalCollection;
    11. import org.apache.shiro.util.ByteSource;
    12. import org.springframework.beans.factory.annotation.Autowired;
    13. import org.springframework.stereotype.Component;
    14. @Component
    15. public class MyRealm extends AuthorizingRealm {
    16. @Autowired
    17. private IUserService service;
    18. /**
    19. * 授权信息
    20. * @param principalCollection
    21. * @return
    22. */
    23. @Override
    24. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    25. return null;
    26. }
    27. /**
    28. * 认证信息
    29. * @param authenticationToken
    30. * @return
    31. * @throws AuthenticationException
    32. */
    33. @Override
    34. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    35. //1获取用户身份信息
    36. String username = authenticationToken.getPrincipal().toString();
    37. //2调用业务层获取用户信息(数据库)
    38. User user = service.queryUserInfoByName(username);
    39. //3非空判断,将数据封装返回
    40. if (user != null){
    41. AuthenticationInfo info = new SimpleAuthenticationInfo(
    42. authenticationToken.getPrincipal(),
    43. user.getPwd(),
    44. ByteSource.Util.bytes("salt"),
    45. authenticationToken.getPrincipal().toString()
    46. );
    47. return info;
    48. }
    49. return null;
    50. }
    51. }

    7. ShiroConfig

    1. package com.jmh.springbootshiro.config;
    2. import com.jmh.springbootshiro.utls.MyRealm;
    3. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
    4. import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
    5. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.context.annotation.Bean;
    8. import org.springframework.context.annotation.Configuration;
    9. @Configuration
    10. public class ShiroConfig {
    11. @Autowired
    12. private MyRealm myRealm;
    13. /**
    14. * 配置SecurityManager
    15. * @return
    16. */
    17. @Bean
    18. public DefaultWebSecurityManager defaultWebSecurityManager(){
    19. //1创建defaultWebSecurityManager 对象
    20. DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
    21. //2创建加密对象,设置相关属性
    22. HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    23. //2.1采用md5加密
    24. matcher.setHashAlgorithmName("MD5");
    25. //2.2迭代加密次数
    26. matcher.setHashIterations(3);
    27. //3将加密对象存储到myRealm中
    28. myRealm.setCredentialsMatcher(matcher);
    29. //4将myRealm存入defaultWebSecurityManager 对象
    30. defaultWebSecurityManager.setRealm(myRealm);
    31. return defaultWebSecurityManager;
    32. }
    33. }

    8. controller

    1. package com.jmh.springbootshiro.controller;
    2. import org.apache.shiro.SecurityUtils;
    3. import org.apache.shiro.authc.AuthenticationException;
    4. import org.apache.shiro.authc.AuthenticationToken;
    5. import org.apache.shiro.authc.UsernamePasswordToken;
    6. import org.apache.shiro.subject.Subject;
    7. import org.springframework.web.bind.annotation.RequestMapping;
    8. import org.springframework.stereotype.Controller;
    9. import org.springframework.web.bind.annotation.RestController;
    10. /**
    11. *

    12. * 用户表 前端控制器
    13. *

    14. *
    15. * @author jmh
    16. * @since 2022-11-13
    17. */
    18. @RestController
    19. @RequestMapping("/user")
    20. public class UserController {
    21. @RequestMapping("/login")
    22. public String login(String name,String pwd){
    23. //1获取subject对象
    24. Subject subject = SecurityUtils.getSubject();
    25. //2封装请求数据到token
    26. AuthenticationToken token = new UsernamePasswordToken(name,pwd);
    27. //3调用login方法进行登录认证
    28. try {
    29. subject.login(token);
    30. return "登录成功";
    31. } catch (AuthenticationException e) {
    32. e.printStackTrace();
    33. return "登录失败";
    34. }
    35. }
    36. @RequestMapping("/test")
    37. public String test(){
    38. return "test";
    39. }
    40. }

    9. 配置application.yml文件

    1. server:
    2. port: 8080
    3. spring:
    4. application:
    5. name: shiro
    6. datasource:
    7. driver-class-name: com.mysql.jdbc.Driver
    8. url: jdbc:mysql://localhost:3306/shirodb?characterEncoding=utf-8&useSSL=false
    9. username: root
    10. password: 1234
    11. jackson:
    12. date-format: yyyy-MM-dd HH:mm:ss
    13. time-zone: GMT+8
    14. #整合mybatisPlus
    15. mybatis-plus:
    16. #配置SQL映射文件路径
    17. mapper-locations: classpath:mapper/*.xml
    18. #配置日志输出
    19. logging:
    20. level:
    21. com.jmh.springbootshiro.mapper: debug
    22. #开放shiro认证信息访问路径
    23. shiro:
    24. loginUrl: /user/login

    10. 配置启动类

    1. package com.jmh.springbootshiro;
    2. import org.mybatis.spring.annotation.MapperScan;
    3. import org.springframework.boot.SpringApplication;
    4. import org.springframework.boot.autoconfigure.SpringBootApplication;
    5. @SpringBootApplication
    6. @MapperScan("com.jmh.springbootshiro.mapper")
    7. public class SpringbootShiroApplication {
    8. public static void main(String[] args) {
    9. SpringApplication.run(SpringbootShiroApplication.class, args);
    10. }
    11. }

     11. 启动项目开始测试

     

  • 相关阅读:
    25.flink上下游算子之间数据是如何流动的(重要)
    C# 中,使用 LINQ 示例 备忘
    【CodeForces】CF10D LCIS
    liunx python3连接oracle
    英语口语学习(2)
    LeetCode 面试题 04.03. 特定深度节点链表
    【langchain手把手2】构造Prompt模版
    CLAHE 算法学习 matlab
    用于单细胞多组学整合的无监督拓扑对齐方法
    【Git学习二】时光回溯:git reset和git checkout命令详解
  • 原文地址:https://blog.csdn.net/m0_63300795/article/details/127833977